バイナリツリーを考えると、そのノードの値の先行順走査を返します。
例:
入力:[1、NULL、2,3]
1
2
/
3
出力:[1,2,3]
フォローアップ:、再帰的解決策は簡単です、あなたが繰り返しそれを行うだろうか?
二つの方法の反復と再帰があります。
func preorderTraversal(root *TreeNode) []int {
if root == nil {
return []int{}
}
res := []int{}
preOrder(root, &res)
return res
}
func preOrder(root *TreeNode, ans *[]int) {
if root == nil {
return
}
*ans = append(*ans, root.Val)
preOrder(root.Left, ans)
preOrder(root.Right, ans)
}