C++實現LeetCode(102.二叉樹層序遍歷)

[LeetCode] 102. Binary Tree Level Order Traversal 二叉樹層序遍歷

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
/ \
9  20
/  \
15   7

return its level order traversal as:

[
[3],
[9,20],
[15,7]
]

層序遍歷二叉樹是典型的廣度優先搜索 BFS 的應用,但是這裡稍微復雜一點的是,要把各個層的數分開,存到一個二維向量裡面,大體思路還是基本相同的,建立一個 queue,然後先把根節點放進去,這時候找根節點的左右兩個子節點,這時候去掉根節點,此時 queue 裡的元素就是下一層的所有節點,用一個 for 循環遍歷它們,然後存到一個一維向量裡,遍歷完之後再把這個一維向量存到二維向量裡,以此類推,可以完成層序遍歷,參見代碼如下:

解法一:

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        if (!root) return {};
        vector<vector<int>> res;
        queue<TreeNode*> q{{root}};
        while (!q.empty()) {
            vector<int> oneLevel;
            for (int i = q.size(); i > 0; --i) {
                TreeNode *t = q.front(); q.pop();
                oneLevel.push_back(t->val);
                if (t->left) q.push(t->left);
                if (t->right) q.push(t->right);
            }
            res.push_back(oneLevel);
        }
        return res;
    }
};

下面來看遞歸的寫法,核心就在於需要一個二維數組,和一個變量 level,關於 level 的作用可以參見博主的另一篇博客 Binary Tree Level Order Traversal II 中的講解,參見代碼如下:

解法二:

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        levelorder(root, 0, res);
        return res;
    }
    void levelorder(TreeNode* node, int level, vector<vector<int>>& res) {
        if (!node) return;
        if (res.size() == level) res.push_back({});
        res[level].push_back(node->val);
        if (node->left) levelorder(node->left, level + 1, res);
        if (node->right) levelorder(node->right, level + 1, res);
    }
};

Github 同步地址:

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

類似題目:

Binary Tree Level Order Traversal II

Binary Tree Zigzag Level Order Traversal

Minimum Depth of Binary Tree

Binary Tree Vertical Order Traversal 

Average of Levels in Binary Tree

N-ary Tree Level Order Traversal

參考資料:

https://leetcode.com/problems/binary-tree-level-order-traversal/

https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/33445/Java-Solution-using-DFS

https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/33450/Java-solution-with-a-queue-used

https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/114449/A-general-approach-to-level-order-traversal-questions-in-Java

到此這篇關於C++實現LeetCode(102.二叉樹層序遍歷)的文章就介紹到這瞭,更多相關C++實現二叉樹層序遍歷內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: