题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
package main
import . "nc_tools"
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
*
* @param root TreeNode类 the root of binary tree
* @return int整型二维数组
*/
var pre = make([]int, 0)
var mid = make([]int, 0)
var nex = make([]int, 0)
func threeOrders( root *TreeNode ) [][]int {
preTrave(root)
midTrave(root)
nexTrave(root)
res := make([][]int, 3)
res[0] = pre
res[1] = mid
res[2] = nex
return res
}
func preTrave(root *TreeNode ) {
if root == nil {
return
}
pre = append(pre, root.Val)
preTrave(root.Left)
preTrave(root.Right)
}
func midTrave(root *TreeNode ) {
if root == nil {
return
}
midTrave(root.Left)
mid = append(mid, root.Val)
midTrave(root.Right)
}
func nexTrave(root *TreeNode ) {
if root == nil {
return
}
nexTrave(root.Left)
nexTrave(root.Right)
nex = append(nex, root.Val)
}