标签:
Count Complete Tree Nodes
问题:
Given a complete binary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
思路:
分治法的应用
他人代码:
public class Solution { public int countNodes(TreeNode root) { if(root == null) return 0; int h = getHeight(root); return getHeight(root.right)==h-1 ? (1<<(h-1)) + countNodes(root.right) : (1<<(h-2)) + +countNodes(root.left); } public int getHeight(TreeNode root) { return root==null ? 0 : 1+getHeight(root.left); } }
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4581317.html