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.
Ideas
Calculate the height of the left and right subtree of the root node, if the height is equal, it is full two fork tree, node points directly using formula calculation: 2^h-1;
Otherwise, a recursive call is Countnodes (left) + countnodes (right) + 1.
Time/Space complexity
The best case is full two fork tree, time complexity is O (h);
The worst case is O (n) (? )
Program
/** * Definition for a binary tree node. * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */public class Solution {public int countnodes (TreeNode root) {if (root = null) {return 0; } int lh = getleftheight (root); int RH = Getrightheight (root); if (LH = = RH) {return (1 << LH)-1; } return Countnodes (root.left) + countnodes (root.right) + 1; } private static int getleftheight (TreeNode root) {if (root = null) {return 0; } int count = 0; while (root = null) {++count; root = Root.left; } return count; } private static int getrightheight (TreeNode root) {if (root = null) {return 0; } int count = 0; while (root = null) {++count; Root = Root.right; } return count; }}
Count Complete Tree Nodes