LeetCode/107. Binary Tree Level Order Traversal II.md

47 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [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;
}
};
```