1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class Solution { public int countNodes(TreeNode root) { if (root == null) return 0; int ans = 1; int l = calHeight(root.left); int r = calHeight(root.right); if (l == r) { ans += (1 << l) - 1; ans += countNodes(root.right); } else { ans += (1 << r) - 1; ans += countNodes(root.left); } return ans; }
public int calHeight(TreeNode node) { if (node == null) return 0; return calHeight(node.left) + 1; } }
|