LeetCode 「简单」145.二叉树的后序遍历
题目描述
给定一个二叉树的根节点 root ,返回 它的 后序 遍历 。
示例
输入:root = [1,null,2,3]
输出:[3,2,1]
输入:root = [1,2,3,4,5,null,8,null,null,6,7,9]
输出:[4,6,7,5,2,9,8,3,1]
输入:root = []
输出:[]
输入:root = [1]
输出:[1]
解答
递归
Code
/**
* 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 [];
const result = [];
const dfs = (node) => {
if (!node) return;
dfs(node.left);
dfs(node.right);
result.push(node.val);
};
dfs(root);
return result;
};
迭代
思路
- 使用栈
- 使用一个栈来模拟递归调用的过程
- 栈用于存储尚未处理的节点
- 初始化
- 将根节点压入栈中
- 遍历逻辑
- 当栈不为空时,执行以下操作:
- 弹出栈顶节点,访问该节点(将其值添加到结果数组中)
- 将左子节点压入栈(如果存在)
- 将右子节点压入栈(如果存在)
- 由于栈是后进先出(LIFO)结构,先压入左子节点,再压入右子节点,这样在弹出时右子节点会先被处理
- 反转结果数组
- 由于后序遍历的顺序是左 -> 右 -> 根,而我们实际上是按照根 -> 右 -> 左的顺序访问节点,因此最后需要将结果数组反转
Code
/**
* 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 [];
const result = [];
const stack = [root];
while (stack.length) {
const node = stack.pop();
result.push(node.val);
if (node.left) stack.push(node.left);
if (node.right) stack.push(node.right);
}
return result.reverse();
};
