「每日LeetCode」2020年9月29日

本文最后更新于:2023年3月19日 晚上

Lt145. 二叉树的后序遍历

145. 二叉树的后序遍历

给定一个二叉树,返回它的 后序  *遍历。
*
示例:**

1
2
3
4
5
6
7
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

思路

递归

正常递归后序遍历即可

迭代

二叉树的后序遍历
如果有左子树,就先一直将左节点放入栈中,直到出现左子树为空。出栈一个元素,判断右子树是不是也为空:如果右子树不为空,将当前节点重新加入栈中,并将 root 指向右子树,重新进行以上过程;如果为空,则是叶子节点,将其加入结果数组,将 root 设为空,表示跳过向左遍历的过程;并将 prev 设为该节点,防止当前节点重复进入右子树。

解答

递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function (root) {
const res = [];
const visit = (root) => {
if (!root) return null;
visit(root.left);
visit(root.right);
res.push(root.val);
};
visit(root);
return res;
};

迭代

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function (root) {
if (!root) return null;
const res = [];
const temp = [];
temp.push(root);
root = root.left;
let prev = null;
while (root || temp.length) {
while (root) {
temp.push(root);
root = root.left;
}

root = temp.pop();
if (!root.right || root.right === prev) {
res.push(root.val);
prev = root;
root = null;
} else {
temp.push(root);
root = root.right;
}
}
return res;
};