LeetCode107 Binary Tree Level Order Traversal II

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

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).

样例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Input:
Given binary tree [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7

Output:
[
[15,7],
[9,20],
[3]
]

思路

求二叉树层序遍历的逆序。

BFS一遍即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* 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>> ans;
if (root == NULL) return ans;
queue<pair<TreeNode*, int>> que;
que.push(make_pair(root, 1));
vector<int> temp;
int pre = 1;
while (!que.empty()) {
pair<TreeNode*, int>& p = que.front();
que.pop();
if (p.second != pre) {
ans.push_back(temp);
temp.clear();
pre = p.second;
}
temp.push_back(p.first->val);
if (p.first->left != NULL) que.push(make_pair(p.first->left, p.second + 1));
if (p.first->right != NULL) que.push(make_pair(p.first->right, p.second + 1));
}
ans.push_back(temp);
reverse(ans.begin(), ans.end());
return ans;
}
};
分享到 评论