-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode222.java
51 lines (48 loc) · 1.29 KB
/
leetcode222.java
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
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/*
Solution: According to defination of complete binary tree, if height(left) == height(right) => this tree is a full binary tree; else, recursively calculate the # of nodes
*/
public class Solution {
public int countNodes(TreeNode root) {
if(root == null)
return 0;
int left = getLeft(root.left);
int right = getRight(root.right);
/* System.out.println(left);
System.out.println(right);*/
if(left == right){
return (2<<(left)) - 1;
}
else{
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
private int getLeft(TreeNode root) {
if(root == null)
return 0;
int count = 0;
while(root.left!=null) {
root = root.left;
++count;
}
return count+1;
}
private int getRight(TreeNode root) {
if(root == null)
return 0;
int count = 0;
while(root.right!=null) {
root = root.right;
++count;
}
return count+1;
}
}