二叉树的后序遍历

描述
给定一个二叉树,返回他的后序遍历的序列。

题解

  • 遍历左子树
  • 遍历右子树
  • 打印根节点
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
package main

type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}

/**
*
*
* @param root TreeNode类
* @return int整型一维数组
*/
func postorderTraversal( root *TreeNode ) []int {
// write code here
postorderVals := make([]int, 0)
postorder(&postorderVals, root)
return postorderVals
}

func postorder(res *[]int, root *TreeNode) {
if root == nil {
return
}
postorder(res, root.Left)
postorder(res, root.Right)
*res = append(*res, root.Val)
}