mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-05 00:25:22 +08:00
73 lines
1.4 KiB
Go
73 lines
1.4 KiB
Go
package leetcode
|
|
|
|
import (
|
|
"github.com/halfrost/LeetCode-Go/structures"
|
|
)
|
|
|
|
// TreeNode define
|
|
type TreeNode = structures.TreeNode
|
|
|
|
/**
|
|
* Definition for a binary tree node.
|
|
* type TreeNode struct {
|
|
* Val int
|
|
* Left *TreeNode
|
|
* Right *TreeNode
|
|
* }
|
|
*/
|
|
|
|
// 解法一 递归
|
|
func preorderTraversal(root *TreeNode) []int {
|
|
res := []int{}
|
|
if root != nil {
|
|
res = append(res, root.Val)
|
|
tmp := preorderTraversal(root.Left)
|
|
for _, t := range tmp {
|
|
res = append(res, t)
|
|
}
|
|
tmp = preorderTraversal(root.Right)
|
|
for _, t := range tmp {
|
|
res = append(res, t)
|
|
}
|
|
}
|
|
return res
|
|
}
|
|
|
|
// 解法二 递归
|
|
func preorderTraversal1(root *TreeNode) []int {
|
|
var result []int
|
|
preorder(root, &result)
|
|
return result
|
|
}
|
|
|
|
func preorder(root *TreeNode, output *[]int) {
|
|
if root != nil {
|
|
*output = append(*output, root.Val)
|
|
preorder(root.Left, output)
|
|
preorder(root.Right, output)
|
|
}
|
|
}
|
|
|
|
// 解法三 非递归,用栈模拟递归过程
|
|
func preorderTraversal2(root *TreeNode) []int {
|
|
if root == nil {
|
|
return []int{}
|
|
}
|
|
stack, res := []*TreeNode{}, []int{}
|
|
stack = append(stack, root)
|
|
for len(stack) != 0 {
|
|
node := stack[len(stack)-1]
|
|
stack = stack[:len(stack)-1]
|
|
if node != nil {
|
|
res = append(res, node.Val)
|
|
}
|
|
if node.Right != nil {
|
|
stack = append(stack, node.Right)
|
|
}
|
|
if node.Left != nil {
|
|
stack = append(stack, node.Left)
|
|
}
|
|
}
|
|
return res
|
|
}
|