/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { Public intcountnodes (TreeNode root) {if(root==NULL) return0; //get to the left and right two depths intLeftdepth=getleftdepth (Root) +1; intRightdepth=getrightdepth (Root) +1; if(leftdepth==rightdepth) { //bit arithmetic is used here to make the actual complexity even lower, and if the POW calculation is called, it will time out . return(2<< (LeftDepth-1))-1; //return (int) Math.pow (2,leftdepth)-1; } Else { returnCountnodes (Root.left) +countnodes (root.right) +1; } } Public intgetleftdepth (TreeNode root) {intRes=0; TreeNode Temp=Root.left; while(temp!=NULL) {res++; Temp=Temp.left; } returnRes; } Public intgetrightdepth (TreeNode root) {intRes=0; TreeNode Temp=Root.right; while(temp!=NULL) {res++; Temp=Temp.right; } returnRes; } }
222. Count Complete Tree Nodes