给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
数据范围:二叉树的节点数量满足
,二叉树节点的值满足
,树的各节点的值各不相同
示例 1:
func preorderTraversal( root *TreeNode ) []int {
// write code here
var res []int
peorder(&res, root)
return res
}
func peorder(res *[]int, root *TreeNode){
if root == nil{
return
}
*res = append(*res, root.Val)
peorder(res, root.Left)
peorder(res, root.Right)
} func preorderTraversal(root *TreeNode) []int {
res:=make([]int,0)
cur, mostRight := root, &TreeNode{}
for cur != nil {
mostRight = cur.Left
if mostRight != nil {
for mostRight.Right != nil && mostRight.Right != cur {
mostRight = mostRight.Right
}
if mostRight.Right != cur {
res = append(res, cur.Val)
mostRight.Right = cur
cur = cur.Left
continue
} else {
mostRight.Right = nil
}
}else{
res = append(res, cur.Val)
}
cur = cur.Right
}
return res
} package main
// import "fmt"
import . "nc_tools"
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型一维数组
*/
var res = []int{}
func preorderTraversal( root *TreeNode ) []int {
// 方法1:遍历的思维模式
// 通过遍历一遍二叉树得到答案。用一个 traverse 函数配合外部变量来实现。
traverse(root)
return res
}
func traverse(root *TreeNode) {
if root == nil {
return
}
res = append(res, root.Val)
traverse(root.Left)
traverse(root.Right)
}