Topic:
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, was completely filled, and all nodes As far left as possible. It can has between 1 and 2H nodes inclusive at the last level H.
Solving:
If you use the usual solution to traverse one by one, it is O (n) time complexity, will not pass, this side will not write O (n) code. Because it is a completely binary tree, full two fork tree has a nature is the number of nodes equals 2^h-1,h height, so you can judge the height of the node is not the same, if it is the same as the description is full of two fork tree, you can use just the formula, if the left and right are not equal to the recursive calculation of the left node.
Code:
public static int countnodes (TreeNode root) {if (root==null) return 0; else {int left=getleftheight (root); int Right=getrig Htheight (Root), if (left==right) return (1<<left) -1;else {return countnodes (root.right) +countnodes (root.left) + 1;}} public static int getrightheight (TreeNode root) {int height=0, while (root!=null) {height++; root=root.left;} return height;} public static int getleftheight (TreeNode root) {int height=0, while (root!=null) {height++; root=root.right;} return Height;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
LeetCode222 Count Completetree Nodes (calculates the number of nodes for a complete binary tree) Java