forked from terrytong0876/LintCode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathComplete Binary Tree.java
executable file
·92 lines (76 loc) · 1.9 KB
/
Complete Binary Tree.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
E
BFS
Use a flag . 当出现了第一次有 null children的node的时候,
说明complete tree的最低level出现了。
自此以后,queue再不该有node再有child, queue后面出现的node的左右孩子应该都是null.
```
/*
Check a binary tree is completed or not. A complete binary tree is not binary tree that every level is completed filled except the deepest level. In the deepest level, all nodes must be as left as possible. See more definition
Have you met this question in a real interview? Yes
Example
1
/ \
2 3
/
4
is a complete binary.
1
/ \
2 3
\
4
is not a complete binary.
Challenge
Do it in O(n) time
Tags Expand
Binary Tree
*/
/*
Thoughts:
Do a BFS.
Once null occur, all the rest following it has to be null
*/
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root, the root of binary tree.
* @return true if it is a complete binary tree, or false.
*/
public boolean isComplete(TreeNode root) {
if (root == null) {
return true;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
boolean flag = false;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (flag && (node.left != null || node.right != null)) {
return false;
}
if (node.left == null && node.right != null) {
return false;
} else if (node.left == null || node.right == null) {
flag = true;
}
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
return true;
}
}
```