1 and 2h nodes inclusive at the last level H.
Using the brute force method, the recursive asks for a timeout O (N). If the height from a node to the left is always to the right, then the subtree rooted in that node must be perfect binary tree. The number of nodes of the perfect binary tree can be calculated using a formula 2^h-1. If the height is unequal, the return Countnode (left) + Countnode (right) + 1 is called recursively. Complexity of O (h^2)
1 /**2 * Definition for a binary tree node.3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten Public classSolution { One Public intcountnodes (TreeNode root) { A if(Root = =NULL)return0; - intLeftheight =Countleft (root.left); - intRightheight =countright (root.right); the if(Leftheight = = rightheight) {//Perfect binary Tree - return(1<< (leftheight+1))-1; - } - Else returnCountnodes (Root.left) + countnodes (root.right) + 1; + } - + Public intcountleft (TreeNode root) { A intres = 0; at while(Root! =NULL) { -res++; -Root =Root.left; - } - returnRes; - } in - Public intcountright (TreeNode root) { to intres = 0; + while(Root! =NULL) { -res++; theRoot =Root.right; * } $ returnRes;Panax Notoginseng } - the}
Leetcode:count Complete Tree Nodes