二叉树的层次遍历
来源:互联网 发布:马丁全单吉他知乎 编辑:程序博客网 时间:2024/05/24 03:37
问题描述:
给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
样例:
给一棵二叉树 {3,9,20,#,#,15,7}
:
3 / \9 20 / \ 15 7
返回他的分层遍历结果:
[ [3], [9,20], [15,7]]
解题思路:
用两个队列交替使用存储,将根节点放在队列0里,然后用循环取出来将孩子放在另个队列,接着第二次循环在访问另一个队列,做相同的操作。
代码:
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution { /** * @param root: The root of binary tree. * @return: Level order a list of lists of integer */public: vector<vector<int> >tree; vector<vector<int>> levelOrder(TreeNode *root) { // write your code here TreeNode *q; if (root== NULL) return tree; queue<TreeNode *> tem[2]; tem[0].push(root); int i= 0; while (!tem[0].empty() || !tem[1].empty()) { vector<int> a; while (!tem[i].empty()) { a.push_back(tem[i].front()->val); if (tem[i].front()->left!= NULL) tem[(i+1)%2].push(tem[i].front()->left); if (tem[i].front()->right!= NULL) tem[(i+1)%2].push(tem[i].front()->right); tem[i].pop(); } tree.push_back(a); i=(i+1)%2; } return tree; }};
感想:
借鉴的思路,感觉在逻辑上是很好的在思路。
0 0
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历!!!
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- this class is not key value coding-compliant for the key '***'的解决方案
- __dirname cwd() 的区别
- 红帽系统管理学习II 03系统延迟及定时机制
- 使用Nexus搭建Maven私服
- ES6核心知识
- 二叉树的层次遍历
- OpenWRT菜单功能配置
- ipv4头部可选项和ipv6头部的区别
- 把排序数组转换为高度最小的二叉搜索树
- 手动获取spring的ApplicationContext和bean对象
- GMIC2017未来零售峰会单场门票开放
- Android Paint API总结和使用方法
- android activity启动模式
- WPF&MVVM线程问题(progressbar为例)