天机阁

145. 二叉树的后序遍历

2022-07-09 · 1 min read
LeetCode

题目

给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历

难度:🌟🌟

示例 1:

输入:root = [1,null,2,3]
输出:[3,2,1]

示例 2:

输入:root = []
输出:[]

示例 3:

输入:root = [1]
输出:[1]

提示:

  • 树中节点的数目在范围 [0, 100] 内
  • -100 <= Node.val <= 100

题解

定义一个后序遍历递归方法,遍历节点时使用外部变量保存节点。

代码实现

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

// postorderTraversal 145. 二叉树的后序遍历
func postorderTraversal(root *TreeNode) (res []int) {
	if root == nil {
		return nil
	}
	var postorder func(node *TreeNode)
	postorder = func(node *TreeNode) {
		if node == nil {
			return
		}
		postorder(node.Left)
		postorder(node.Right)
		res = append(res, node.Val)
		return
	}

	postorder(root)
	return
}