二叉树的后序遍历
- https://leetcode.cn/problems/binary-tree-postorder-traversal/
描述
- 给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。
示例 1
输入:root = [1,null,2,3]
输出:[3,2,1]
示例 2
输入:root = []
输出:[]
示例 3
输入:root = [1]
输出:[1]
提示
- 树中节点的数目在范围 [0, 100] 内
- -100 <= Node.val <= 100
进阶:递归算法很简单,你可以通过迭代算法完成吗?
Typescript 版算法实现
1 )方案 1
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function postorderTraversal(root: TreeNode | null): number[] {
const result: number[] = []
const isValid = (val: any) => val !== null;
const postorderHandler = (root: TreeNode | null) => {
if(!root) return result;
isValid(root.left) && postorderHandler(root.left);
isValid(root.right) && postorderHandler(root.right);
isValid(root.val) && result.push(root.val);
return result;
}
return postorderHandler(root)
};
- 同前序和中序,这是递归版,递归版真香, 代码及其简洁, 缺点也很明显
- 后续遍历特点
- 对根节点的左子树进行后续遍历
- 对根节点的右子树进行后续遍历
- 访问根节点
- 记忆:左右根
2 )方案 2
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function postorderTraversal(root: TreeNode | null): number[] {
if(!root) return [];
const res: number[] =[];
const stack: TreeNode[] = [];
let cur = root;
stack.push(root);
while(stack?.length) {
cur = stack.pop()!;
res.push(cur.val);
if(cur.left) stack.push(cur.left);
if(cur.right) stack.push(cur.right);
}
return res.reverse();
};
- 这是官方提供的示例,迭代版本,使用栈的特性:后进先出
- 这里用到一个逆向思维,从顶点开始,而非从叶子节点开始
- 根节点值先进栈,之后左节点入栈,之后右节点入栈
- 当while继续时,右节点先出栈(后进先出) 并压进结果栈
- 之后继续找右节点的左右节点,循环处理,直到没有孩子节点
- 在一个最小规模的场景下,比如一棵树只有左右根,那么这个顺序就是
- 根右左,这是最小规模的场景,也是我们的切入点
- 这样reverse之后就是 左右根 这样的顺序了
- 之前是从根节点开始的,这样就把顺序捋正了,从叶子节点开始
- 这个是一种新的思路
3 )方案
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function postorderTraversal(root: TreeNode | null): number[] {
const ans = <number[]>[]; // 存放最终集合
const stack = <TreeNode[]>[]; // 存放树节点集合的栈
let cur = root; // 当前节点
while(cur || stack.length) {
while(cur) {
ans.push(cur.val); // 根的值
stack.push(cur);
cur = cur.right; // 右节点
}
if(stack.length){
cur = stack.pop();
cur = cur.left; // 左节点
}
}
return ans.reverse();
}
- 这是前序遍历方案2和本方案2结合的思路
- 先访问最深层根叶子节点,用一个栈进行来回捯饬
- 最后在用一个reverse进行反转,这也提供一种新的思路
Python3 版算法实现
1 ) 方案1 递归版
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
result = []
def postorderHandler(node: Optional[TreeNode]):
if not node:
return
postorderHandler(node.left)
postorderHandler(node.right)
result.append(node.val)
postorderHandler(root)
return result
2 ) 方案2 迭代法(使用栈)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
res = []
stack = [root]
cur = root
while stack:
cur = stack.pop()
res.append(cur.val)
if cur.left:
stack.append(cur.left)
if cur.right:
stack.append(cur.right)
return res[::-1]
3 ) 方案3 迭代法(使用栈,不同顺序)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans = []
stack = []
cur = root
while cur or stack:
while cur:
ans.append(cur.val)
stack.append(cur)
cur = cur.right
if stack:
cur = stack.pop()
cur = cur.left
return ans[::-1]
Golang 版算法实现
1 )方案1 递归版
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func postorderTraversal(root *TreeNode) []int {
if root == nil {
return []int{}
}
res := []int{}
stack := []*TreeNode{root}
for len(stack) > 0 {
cur := stack[len(stack)-1]
stack = stack[:len(stack)-1]
res = append(res, cur.Val)
if cur.Left != nil {
stack = append(stack, cur.Left)
}
if cur.Right != nil {
stack = append(stack, cur.Right)
}
}
// Reverse the result
for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
res[i], res[j] = res[j], res[i]
}
return res
}
2 )方案2 迭代版(使用栈)
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func postorderTraversal(root *TreeNode) []int {
if root == nil {
return []int{}
}
res := []int{}
stack := []*TreeNode{root}
for len(stack) > 0 {
cur := stack[len(stack)-1]
stack = stack[:len(stack)-1]
res = append(res, cur.Val)
if cur.Left != nil {
stack = append(stack, cur.Left)
}
if cur.Right != nil {
stack = append(stack, cur.Right)
}
}
// Reverse the result
for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
res[i], res[j] = res[j], res[i]
}
return res
}
3 )方案3 迭代版(使用栈,不同顺序)
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func postorderTraversal(root *TreeNode) []int {
ans := []int{}
stack := []*TreeNode{}
cur := root
for cur != nil || len(stack) > 0 {
for cur != nil {
ans = append(ans, cur.Val)
stack = append(stack, cur)
cur = cur.Right
}
if len(stack) > 0 {
cur = stack[len(stack)-1]
stack = stack[:len(stack)-1]
cur = cur.Left
}
}
// Reverse the result
for i, j := 0, len(ans)-1; i < j; i, j = i+1, j-1 {
ans[i], ans[j] = ans[j], ans[i]
}
return ans
}
455



被折叠的 条评论
为什么被折叠?



