leetcode: Binary Tree Level Order Traversal II
来源:互联网 发布:jquery 数组遍历 编辑:程序博客网 时间:2024/05/29 10:13
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,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3]]和I一样,只要插入的时候插入到res的begin()就可以了
/** * Definition for binary tree * 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> > res; if( root == NULL) return res; vector< int> cur; queue< pair< TreeNode *, int> > q; q.push( make_pair( root, 1)); int level = 1; while( !q.empty()){ pair< TreeNode *, int> tmp = q.front(); q.pop(); if( tmp.first->left) q.push( make_pair( tmp.first->left, tmp.second+1)); if( tmp.first->right) q.push( make_pair( tmp.first->right, tmp.second+1)); if( tmp.second > level){ res.insert( res.begin(), cur); cur.clear(); ++level; } cur.push_back( tmp.first->val); } res.insert( res.begin(), cur); return res; }};
0 0
- LeetCode: Binary Tree Level Order Traversal II
- [LeetCode]Binary Tree Level Order Traversal II
- LeetCode Binary Tree Level Order Traversal II
- [Leetcode] Binary Tree Level Order Traversal II
- LeetCode Binary Tree Level Order Traversal II
- [LeetCode] Binary Tree Level Order Traversal II
- 【leetcode】Binary Tree Level Order Traversal II
- [LeetCode]Binary Tree Level Order Traversal II
- [Leetcode]Binary Tree Level Order Traversal II
- [leetcode]Binary Tree Level Order Traversal II
- LeetCode-Binary Tree Level Order Traversal II
- LeetCode - Binary Tree Level Order Traversal II
- [LeetCode] Binary Tree Level Order Traversal II
- LeetCode | Binary Tree Level Order Traversal II
- LeetCode - Binary Tree Level Order Traversal II
- 【leetcode】Binary Tree Level Order Traversal II
- 【LeetCode】Binary Tree Level Order Traversal II
- [LeetCode] Binary Tree Level Order Traversal II
- Repairman - HDU 3024 dp
- KMP+poj2185
- mysql 冷备注意事项
- java学习之数据类型
- 关于XML文件结构的改造
- leetcode: Binary Tree Level Order Traversal II
- poj 3466 A Simple Problem with Integers
- 黑马程序员_使用ADO.NET
- web前端 严格模式和混杂模式详解
- 接口数据收集
- 维护的JSP网站数据丢失
- NYOJ 14 会场安排问题
- Q9.2
- Android报错及解决方案