/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { * this.val = val; * this.left = left; * this.right = right; * } * } */ public class Solution { public int CountNodes(TreeNode root) { if (root == null) { return 0; } int left = depth(root.left); int right = depth(root.right); if (left == right) { return (1 << left) + CountNodes(root.right); } return (1 << right) + CountNodes(root.left); } private int depth(TreeNode root) { int d = 0; for (; root != null; root = root.left) { ++d; } return d; } }