Create 107. Binary Tree Level Order Traversal II.md

This commit is contained in:
唐树森 2018-11-02 23:13:14 +08:00 committed by GitHub
parent 31511a8689
commit 45af5df13e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,46 @@
# [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;
}
};
```