classSolution { publicintcountNodes(TreeNode root) { if (root == null) { return0; } intleft= countNodes(root.left); intright= countNodes(root.right); return left + right + 1; } }
1 2 3 4 5 6 7
funccountNodes(root *TreeNode)int { if root == nil { return0 } left, right := countNodes(root.Left), countNodes(root.Right) return left + right + 1 }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
funccountNodes(root *TreeNode)int { if root == nil { return0 } left, right := root.Left, root.Right leftDeepth, rightDeepth := 0, 0 for left != nil { left = left.Left leftDeepth++ } for right != nil { right = right.Right rightDeepth++ } if leftDeepth == rightDeepth { // if it is a full binary tree return (2 << leftDeepth) - 1 } return countNodes(root.Left) + countNodes(root.Right) + 1 }