mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
47 lines
1.7 KiB
Markdown
47 lines
1.7 KiB
Markdown
![]() |
# [107. Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/)
|
|||
|
# 思路
|
|||
|
题目的意思就是层序遍历的变形,要逆序输出每一层的节点。为此我们先正常层序遍历并用一个stack记录每一层的节点。然后再依次出栈即可。
|
|||
|
用last指针指向每一层的最后一个节点,每当遍历到这个节点即说明遍历完一层,此时应该将此层所有节点压入栈。last初始为root,
|
|||
|
后面每当遍历完每层最后一个节点后,即将last更新成下一层的最后一个节点,为此需要用一个next_last来不断记录能确定的下一层的最右节点。
|
|||
|
时间复杂度和空间复杂度都是O(n)
|
|||
|
|
|||
|
# C++
|
|||
|
``` C++
|
|||
|
class Solution {
|
|||
|
public:
|
|||
|
vector<vector<int>> levelOrderBottom(TreeNode* root) {
|
|||
|
TreeNode *p, *next_last,*last=root;
|
|||
|
stack<vector<int>>stk;
|
|||
|
queue<TreeNode *>q;
|
|||
|
vector<vector<int>>res;
|
|||
|
if(root == NULL) return res;
|
|||
|
vector<int>tmp; // 存放一层的节点
|
|||
|
q.push(root);
|
|||
|
while(!q.empty()){
|
|||
|
p = q.front();
|
|||
|
q.pop();
|
|||
|
tmp.push_back(p -> val);
|
|||
|
if(p -> left){
|
|||
|
q.push(p -> left);
|
|||
|
next_last = p -> left;
|
|||
|
}
|
|||
|
if(p -> right) {
|
|||
|
q.push(p -> right);
|
|||
|
next_last = p -> right;
|
|||
|
}
|
|||
|
if(p == last){
|
|||
|
stk.push(tmp);
|
|||
|
tmp.clear();
|
|||
|
last = next_last; // 更新last指针
|
|||
|
}
|
|||
|
}
|
|||
|
while(!stk.empty()){
|
|||
|
res.push_back(stk.top());
|
|||
|
stk.pop();
|
|||
|
}
|
|||
|
return res;
|
|||
|
}
|
|||
|
};
|
|||
|
```
|
|||
|
|