[LeetCode] 958. 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.

這道題給了一棵二叉樹,讓我們判斷是否是一棵完全二叉樹 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 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM