mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Update 107. Binary Tree Level Order Traversal II.md
This commit is contained in:
parent
97d2a85124
commit
1549ad4e8f
@ -1,8 +1,10 @@
|
||||
# [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来不断记录能确定的下一层的最右节点。
|
||||
题目的意思就是层序遍历的变形,从下往上、从左往右层序遍历。为此我们先正常层序遍历并用一个stack记录每一层的节点。然后再依次出栈即可。
|
||||
|
||||
下面简单说一下正常的层序遍历(即从上往下、从左往右): 建立一个queue,然后先把根节点放进去,进入while循环,记录此刻的queue大小(设为size),
|
||||
并用一个for循环依次出队并遍历size个元素,此过程要将左右两个子节点入队。一次while循环即可得到一层的所有节点,以此类推,可以完成层序遍历。
|
||||
|
||||
时间复杂度和空间复杂度都是O(n)
|
||||
|
||||
# C++
|
||||
@ -10,31 +12,26 @@
|
||||
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; // 存放一层的节点
|
||||
queue<TreeNode *>q;
|
||||
stack<vector<int>>stk;
|
||||
TreeNode *p;
|
||||
|
||||
q.push(root);
|
||||
while(!q.empty()){
|
||||
vector<int>level; // 记录此层的所有节点
|
||||
for(int i = q.size(); i > 0; i--){
|
||||
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指针
|
||||
level.push_back(p -> val);
|
||||
if(p -> left) q.push(p -> left);
|
||||
if(p -> right) q.push(p -> right); // 如果想从下往上、从右往左层序遍历的话只需把词句和上一句调换位置即可
|
||||
}
|
||||
stk.push(level);
|
||||
}
|
||||
// 上面的过程就是正常的层序遍历过程
|
||||
|
||||
while(!stk.empty()){
|
||||
res.push_back(stk.top());
|
||||
stk.pop();
|
||||
|
Loading…
Reference in New Issue
Block a user