Skip to content

Commit

Permalink
Problem 113 add solutions
Browse files Browse the repository at this point in the history
  • Loading branch information
halfrost committed Sep 15, 2020
1 parent f38c70a commit ec09c8d
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ type TreeNode = structures.TreeNode
* }
*/

// 解法一
func zigzagLevelOrder(root *TreeNode) [][]int {
if root == nil {
return [][]int{}
Expand Down Expand Up @@ -57,3 +58,26 @@ func zigzagLevelOrder(root *TreeNode) [][]int {
}
return res
}

// 解法二 递归
func zigzagLevelOrder0(root *TreeNode) [][]int {
var res [][]int
search(root, 0, &res)
return res
}

func search(root *TreeNode, depth int, res *[][]int) {
if root == nil {
return
}
for len(*res) < depth+1 {
*res = append(*res, []int{})
}
if depth%2 == 0 {
(*res)[depth] = append((*res)[depth], root.Val)
} else {
(*res)[depth] = append([]int{root.Val}, (*res)[depth]...)
}
search(root.Left, depth+1, res)
search(root.Right, depth+1, res)
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ package leetcode
* Right *TreeNode
* }
*/

// 解法一
func zigzagLevelOrder(root *TreeNode) [][]int {
if root == nil {
return [][]int{}
Expand Down Expand Up @@ -98,4 +100,27 @@ func zigzagLevelOrder(root *TreeNode) [][]int {
return res
}

// 解法二 递归
func zigzagLevelOrder0(root *TreeNode) [][]int {
var res [][]int
search(root, 0, &res)
return res
}

func search(root *TreeNode, depth int, res *[][]int) {
if root == nil {
return
}
for len(*res) < depth+1 {
*res = append(*res, []int{})
}
if depth%2 == 0 {
(*res)[depth] = append((*res)[depth], root.Val)
} else {
(*res)[depth] = append([]int{root.Val}, (*res)[depth]...)
}
search(root.Left, depth+1, res)
search(root.Right, depth+1, res)
}

```

0 comments on commit ec09c8d

Please sign in to comment.