欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C++实现LeetCode(102.二叉树层序遍历)

程序员文章站 2022-03-11 08:18:34
[leetcode] 102. binary tree level order traversal 二叉树层序遍历given a binary tree, return the level...

[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 同步地址:

类似题目:

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/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++实现二叉树层序遍历内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!