Binary Tree Preorder Traversal Solutions in Go
Number 144
Difficulty Medium
Acceptance 55.8%
Link LeetCode
Solutions
Go solution by halfrost/LeetCode-Go
package leetcodeimport ("github.com/halfrost/LeetCode-Go/structures")// TreeNode definetype 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 []intpreorder(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}