-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathSolution.java
More file actions
38 lines (38 loc) · 827 Bytes
/
Solution.java
File metadata and controls
38 lines (38 loc) · 827 Bytes
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
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int countNodes(TreeNode root) {
if (root==null) {
return 0;
}
int l=getLeft(root);
int r=getRight(root);
if (l==r) {
return (2<<(l-1)) - 1;
}
return 1+countNodes(root.left) + countNodes(root.right) ;
}
public int getLeft(TreeNode root){
int h=0;
while(root!=null){
h++;
root=root.left;
}
return h;
}
public int getRight(TreeNode root){
int h=0;
while(root!=null){
h++;
root=root.right;
}
return h;
}
}