1. 程式人生 > 實用技巧 >[LeetCode] 958. Check Completeness of a Binary Tree 檢查二叉樹的完全性

[LeetCode] 958. Check Completeness of a Binary Tree 檢查二叉樹的完全性


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

Definition of a complete binary tree fromWikipedia:
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 2hnodes 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.

這道題給了一棵二叉樹,讓我們判斷是否是一棵完全二叉樹 Complete Binary Tree,通過題目中的解釋可知,完全二叉樹除了最後一行之外,所有位置都是滿員的,而且最後一行的結點都是儘可能靠左的,注意跟完滿二叉樹 Full Bianry Tree 區分開來。最簡單直接的方法就是按層序遍歷二叉樹,當遇到空結點時,後面若還出現非空結點,則一定不是完全二叉樹。具體到寫法就是先把根結點放入到佇列中,然後進行迴圈,條件是隊首結點不為空。在迴圈中取出隊首結點,然後將其左右子結點加入佇列中,這裡不必判斷子結點是否為空,為空照樣加入佇列,因為一旦取出空結點,迴圈就會停止。然後再用個迴圈將隊首所有的空結點都移除,這樣若是完全二叉樹的話,佇列中所有還剩的結點都應該是空結點,且都會被移除,若佇列中存在非空結點,說明不是完全二叉樹,最後只要判斷佇列是否為空即可,參見程式碼如下:


解法一:

class Solution {
public:
    bool isCompleteTree(TreeNode* root) {
        queue<TreeNode*> q{{root}};
        while (q.front() != NULL) {
            TreeNode *cur = q.front(); q.pop();
            q.push(cur->left);
            q.push(cur->right);
        }
        while (!q.empty() && q.front() == NULL) {
            q.pop();
        }
        return q.empty();
    }
};

下面這種解法思想都一樣,只不過寫法略有不同,這裡使用了一個變數 found,初始化為 false,然後還是用層序遍歷,當取出的結點為空結點時,比較 found 為 true,然後繼續遍歷。當遍歷到非空結點時,若此時 found 為 true 了,則直接返回 false 即可。當迴圈退出後,返回 true, 參見程式碼如下:


解法二:

class Solution {
public:
    bool isCompleteTree(TreeNode* root) {
        queue<TreeNode*> q{{root}};
        bool found = false;
        while (!q.empty()) {
            TreeNode *cur = q.front(); q.pop();
            if (!cur) {
                found = true;
            } else {
                if (found) return false;
                q.push(cur->left);
                q.push(cur->right);
            }
        }
        return true;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/958


參考資料:

https://leetcode.com/problems/check-completeness-of-a-binary-tree/

https://leetcode.com/problems/check-completeness-of-a-binary-tree/discuss/205682/JavaC%2B%2BPython-BFS-Level-Order-Traversal

https://leetcode.com/problems/check-completeness-of-a-binary-tree/discuss/205768/Java-easy-Level-Order-Traversal-one-while-loop


LeetCode All in One 題目講解彙總(持續更新中...)