题目描述:具体描述见原题。简单来说就是先序遍历二叉树。
解题思路:先访问根节点,遍历左子树,再遍历右子树。具体过程见代码,还是建议采用非递归过程解题。
具体代码:
// 非递归解法
func preorderTraversal(root *TreeNode) []int {
res := make([]int, 0)
if root == nil {
return res
}
s := make([]*TreeNode, 0)
s = append(s, root) // 根节点先入栈
for len(s) != 0 {
n := s[len(s)-1] // 访问根节点
res = append(res, n.Val)
s = s[:len(s)-1]
if n.Right != nil { // 右子树先入栈,后访问
s = append(s, n.Right)
}
if n.Left != nil { // 左子树后入栈,先访问
s = append(s, n.Left)
}
}
return res
}
// 递归解法
func preorderTraversal(root *TreeNode) []int {
res := make([]int, 0)
preorder(root, &res)
return res
}
func preorder(root *TreeNode, output *[]int) {
if root != nil {
*output = append(*output, root.Val) // 访问根节点
preorder(root.Left, output) // 递归遍历左子树
preorder(root.Right, output) // 递归遍历右子树
}
}
补充说明:先序遍历也是常用的基本方法,很多题目以此过程为基础进行拓展。