0145. 二叉树的后序遍历
题目地址(145. 二叉树的后序遍历)
题目描述
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
前置知识
公司
思路
关键点解析
代码
相关专题
最后更新于
这有帮助吗?
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
最后更新于
这有帮助吗?
这有帮助吗?
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function (root) {
// 1. Recursive solution
// if (!root) return [];
// return postorderTraversal(root.left).concat(postorderTraversal(root.right)).concat(root.val);
// 2. iterative solutuon
if (!root) return [];
const ret = [];
const stack = [root];
let p = root; // 标识元素,用来判断节点是否应该出栈
while (stack.length > 0) {
const top = stack[stack.length - 1];
if (
top.left === p ||
top.right === p || // 子节点已经遍历过了
(top.left === null && top.right === null) // 叶子元素
) {
p = stack.pop();
ret.push(p.val);
} else {
if (top.right) {
stack.push(top.right);
}
if (top.left) {
stack.push(top.left);
}
}
}
return ret;
};class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ans;
stack<TreeNode*> s;
TreeNode *prev = NULL;
while (root || s.size()) {
while (root) {
s.push(root);
root = root->left;
}
root = s.top();
if (!root->right || root->right == prev) {
ans.push_back(root->val);
s.pop();
prev = root;
root = NULL;
} else root = root->right;
}
return ans;
}
};