Binary Tree Level Order Traversal II

Total Accepted: 60177 Total Submissions: 188407 Difficulty: Easy

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]
]

code:

/**
* 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(NULL == root) return ret;
queue<TreeNode *> q[2];  // 队列实现层次遍历，需要两个
stack<vector<int>> s;  // 保存中间结果
int cur=0;
q[cur].push(root);
while(!q[cur].empty()) {
vector<int> tmp;
while(!q[cur].empty()) {
TreeNode *p = q[cur].front();
tmp.push_back(p->val);
if(p->left) q[cur^1].push(p->left);  // 交替入队
if(p->right) q[cur^1].push(p->right);
q[cur].pop();
}
cur^=1;
s.push(tmp);
}
while(!s.empty()) {
ret.push_back(s.top());
s.pop();
}
return ret;
}
};

LeetCode 107:Binary Tree Level Order Traversal II

2015-05-31 00:11:23

LeetCode --- 107. Binary Tree Level Order Traversal II

2015-04-17 16:46:33

leetcode 107 Binary Tree Level Order Traversal II C++

2016-05-28 20:57:50

【LeetCode】107. Binary Tree Level Order Traversal II 解题报告

2016-05-26 16:18:51

[LeetCode] Binary Tree Level Order Traversal 二叉树层次遍历(DFS | BFS)

2015-09-11 02:20:37

leetCode解题报告之Binary Tree Level Order Traversal II,I(二叉树层次遍历)

2014-03-28 20:28:01

[LeetCode 107]Binary Tree Level Order Traversal II(递归法）

2016-07-24 17:39:08

LeetCode102 Binary Tree Level Order Traversal Java

2016-04-23 14:20:55

【LeetCode】102. Binary Tree Level Order Traversal 解题报告

2016-05-26 15:06:54

【leetCode】Binary Tree Level Order Traversal python实现

2016-06-19 01:41:14

不良信息举报

LeetCode:Binary Tree Level Order Traversal II