1. 程式人生 > >[Swift Weekly Contest 115]LeetCode958. 二叉樹的完全性檢驗 | Check Completeness of a Binary Tree

[Swift Weekly Contest 115]LeetCode958. 二叉樹的完全性檢驗 | Check Completeness of a Binary Tree

Given a binary tree, determine if it is a complete binary tree.

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

 

Example 1:

Input: [1,2,3,4,5,6]
Output: true
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.

Example 2:

Input: [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.

Note:

  1. The tree will have between 1 and 100 nodes.

給定一個二叉樹,確定它是否是一個完全二叉樹

百度百科中對完全二叉樹的定義如下:

若設二叉樹的深度為 h,除第 h 層外,其它各層 (1~h-1) 的結點數都達到最大個數,第 h 層所有的結點都連續集中在最左邊,這就是完全二叉樹。(注:第 h 層可能包含 1~ 2h 個節點。)

 

示例 1:

輸入:[1,2,3,4,5,6]
輸出:true
解釋:最後一層前的每一層都是滿的(即,結點值為 {1} 和 {2,3} 的兩層),且最後一層中的所有結點({4,5,6})都儘可能地向左。

示例 2:

輸入:[1,2,3,4,5,null,7]
輸出:false
解釋:值為 7 的結點沒有儘可能靠向左側。

提示:

  1. 樹中將會有 1 到 100 個結點。

36 ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     func isCompleteTree(_ root: TreeNode?) -> Bool {
16         var root = root
17         var queue:[TreeNode?] =  [TreeNode?]()
18         var leaf:Bool = false
19         queue.append(root)
20         
21         while(!queue.isEmpty)
22         {
23             root = queue.removeFirst()
24             if (leaf && (root?.left != nil || root?.right != nil)) || (root?.left == nil && root?.right != nil)
25             {
26                 return false
27             }
28             if root?.left != nil
29             {
30                 queue.append(root?.left)
31             }
32             if root?.right != nil
33             {
34                 queue.append(root?.right)
35             }
36             else
37             {
38                 leaf = true
39             }
40         }
41          return true
42     }
43 }