【一天一道LeetCode】#107. Binary Tree Level Order Traversal II
2016-06-29 15:07
267 查看
一天一道LeetCode
本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处
(一)题目
来源: https://leetcode.com/problems/binary-tree-level-order-traversal-ii/Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level >from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
(二)解题
本题大意:按层序从下往上输出二叉树,注意与【一天一道LeetCode】#102. Binary Tree Level Order Traversal解题思路:在上一题的基础上,我偷懒的用了一个resverse函数就将结果反过来输出了。
代码如下:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> levelOrderBottom(TreeNode* root) { vector<vector<int>> ret; if(root==NULL) return ret; queue<TreeNode*> que;//用queue来存储每一层的节点 que.push(root);//初始化 while(!que.empty()) { vector<int> tempVec; queue<TreeNode*> tempque; while(!que.empty())//依次取出节点 { TreeNode* tempNode = que.front();//从左往右 que.pop(); tempVec.push_back(tempNode->val); if(tempNode->left!=NULL) tempque.push(tempNode->left);//处理左子树 if(tempNode->right!=NULL) tempque.push(tempNode->right);//处理右子树 } que = tempque;//que赋值为下一层的节点 ret.push_back(tempVec);//每一层的结果保存下来 } reverse(ret.begin(),ret.end());//反向 return ret; } };
相关文章推荐
- 文件遍历排序函数
- Lua 学习笔记之C API 遍历 Table实现代码
- C#遍历文件夹后上传文件夹中所有文件错误案例分析
- C#中遍历Hashtable的4种方法
- Erlang中遍历取出某个位置的最大值代码
- C++实现图的邻接矩阵存储和广度、深度优先遍历实例分析
- C++实现图的邻接表存储和广度优先遍历实例分析
- 举例讲解C语言程序中对二叉树数据结构的各种遍历方式
- C++非递归队列实现二叉树的广度优先遍历
- php遍历目录方法小结
- 一个目录遍历函数
- php遍历删除整个目录及文件的方法
- PHP遍历文件夹与文件类及处理类用法实例
- PHP遍历XML文档所有节点的方法
- php中使用key,value,current,next和prev函数遍历数组的方法
- C#使用前序遍历、中序遍历和后序遍历打印二叉树的方法
- C#使用foreach遍历哈希表(hashtable)的方法
- php递归遍历多维数组的方法
- C#集合遍历时删除和增加元素的方法
- C#简单遍历指定文件夹中所有文件的方法