Skip to content

Commit fca40b6

Browse files
Create 958. 二叉树的完全性检验.md
1 parent 8472d40 commit fca40b6

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
#### 958. 二叉树的完全性检验
2+
3+
难度:中等
4+
5+
---
6+
7+
给你一棵二叉树的根节点 `root` ,请你判断这棵树是否是一棵 **完全二叉树**  。
8+
9+
在一棵 **[完全二叉树](https://baike.baidu.com/item/完全二叉树/7773232?fr=aladdin)** 中,除了最后一层外,所有层都被完全填满,并且最后一层中的所有节点都尽可能靠左。最后一层(第 `h` 层)中可以包含 `1` 到 `2^h` 个节点。
10+
11+
**示例 1:**
12+
13+
![](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/15/complete-binary-tree-1.png)
14+
15+
```
16+
输入:root = [1,2,3,4,5,6]
17+
输出:true
18+
解释:最后一层前的每一层都是满的(即,节点值为 {1} 和 {2,3} 的两层),且最后一层中的所有节点({4,5,6})尽可能靠左。
19+
```
20+
21+
**示例 2:**
22+
23+
**![](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/15/complete-binary-tree-2.png)**
24+
25+
```
26+
输入:root = [1,2,3,4,5,null,7]
27+
输出:false
28+
解释:值为 7 的节点不满足条件「节点尽可能靠左」。
29+
```
30+
31+
**提示:**
32+
33+
* 树中节点数目在范围 `[1, 100]`
34+
* `1 <= Node.val <= 1000`
35+
36+
---
37+
38+
广度搜索优先:
39+
40+
层序遍历将所有节点(包括空节点)放入队列中,并且检查队列中的节点是否是空节点然后弹出,如果遇到空节点并且后续有节点再插入到队列中,意味着肯定为非完全二叉树。
41+
42+
```Go
43+
/**
44+
* Definition for a binary tree node.
45+
* type TreeNode struct {
46+
* Val int
47+
* Left *TreeNode
48+
* Right *TreeNode
49+
* }
50+
*/
51+
func isCompleteTree(root *TreeNode) bool {
52+
flag := false
53+
queue := []*TreeNode{root}
54+
for len(queue) > 0 {
55+
node := queue[0]
56+
queue = queue[1:]
57+
if node == nil {
58+
flag = true
59+
} else {
60+
if flag == true {
61+
return false
62+
}
63+
queue = append(queue, node.Left)
64+
queue = append(queue, node.Right)
65+
}
66+
}
67+
return true
68+
}
69+
```

0 commit comments

Comments
 (0)