c/c++开发分享C++实现LeetCode(102.二叉树层序遍历)

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

需要了解更多c/c++开发分享C++实现LeetCode(102.二叉树层序遍历),都可以关注C/C++技术分享栏目—猴子技术宅(www.ssfiction.com)

本文来自网络收集,不代表猴子技术宅立场,如涉及侵权请点击右边联系管理员删除。

如若转载,请注明出处:https://www.ssfiction.com/c-cyuyankaifa/675073.html

发表评论

邮箱地址不会被公开。 必填项已用*标注