Leetcode_Binary Tree Level Order Traversal
来源:互联网 发布:程序员 显示器 护眼 编辑:程序博客网 时间:2024/06/05 13:09
广度遍历二叉树,且要分别记录每一层的数据,方法有二。
1.迭代法
设置两个队列,其中一个队列用于存放上一层的节点,另一个队列用于存放下一层的节点。轮番使用。
class Solution {public: vector<vector<int> > levelOrder(TreeNode *root) {queue<TreeNode *> q1,q2;vector<vector<int>> result;if(!root) return result;vector<int> path;q1.push(root);while(!q1.empty()||!q2.empty()){path.clear();while(!q1.empty()){TreeNode *node=q1.front();path.push_back(node->val);if(node->left)q2.push(node->left);if(node->right)q2.push(node->right);q1.pop();}if(!path.empty())result.push_back(path);path.clear();while(!q2.empty()){TreeNode *node=q2.front();path.push_back(node->val);if(node->left)q1.push(node->left);if(node->right)q1.push(node->right);q2.pop();}if(!path.empty())result.push_back(path);} return result; }};2.递归法(来源于网上)
class Solution {public: vector<vector<int> > levelOrder(TreeNode *root) {vector<vector<int>> result;traverse(root,1,result);return result; }private:void traverse(TreeNode *root,int level,vector<vector<int>> &result){if(!root) return;if(level>result.size())result.push_back(vector<int>());result[level-1].push_back(root->val);traverse(root->left,level+1,result);traverse(root->right,level+1,result);}};
0 0
- Leetcode_Binary Tree Level Order Traversal
- LeetCode_binary-tree-level-order-traversal
- Leetcode_binary-tree-level-order-traversal-ii
- leetcode_Binary Tree Level Order Traversal _easy
- LeetCode_Binary Tree Level Order Traversal II
- LeetCode_binary-tree-zigzag-level-order-traversal
- Leetcode_binary-tree-level-order-traversal (updated c++ and python version)
- Leetcode_binary-tree-zigzag-level-order-traversal (updated c++ and python version)
- Level Order Tree Traversal
- Leetcode_binary-tree-preorder-traversal
- Leetcode_binary-tree-inorder-traversal
- Leetcode_binary-tree-postorder-traversal
- LeetCode_Binary Tree Postorder Traversal
- LeetCode_Binary Tree Preorder Traversal
- leetcode_Binary Tree Preorder Traversal
- LeetCode_Binary Tree Inorder Traversal
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal
- Hbase 学习笔记(一): 基础客户端API
- android之网络访问http请求总结
- 汉字在字库中的偏移地址计算、显示方法
- [leetcode]Longest Consecutive Sequence
- 使用Fiddler快速调试线上页面
- Leetcode_Binary Tree Level Order Traversal
- uva1658 Admiral 最小费用最大流
- 念数字
- [JAVA加解密]对登陆密码及网络传输内容加密
- android 的ListView中,判断其已滚动到最顶部或者最底部?
- java在JFrame里 this.setIconImage((new ImageIcon("image\\qq.jpg")).getImage());
- UITapGestureRecognizer会屏蔽掉Button的点击事件
- Hbase 学习笔记(二): 高级模块
- UNIX环境C语言编程(13)-高级进程间通信