Skip to content

Commit ec09c8d

Browse files
committed
Problem 113 add solutions
1 parent f38c70a commit ec09c8d

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

leetcode/0103.Binary-Tree-Zigzag-Level-Order-Traversal/103. Binary Tree Zigzag Level Order Traversal.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ type TreeNode = structures.TreeNode
1616
* }
1717
*/
1818

19+
// 解法一
1920
func zigzagLevelOrder(root *TreeNode) [][]int {
2021
if root == nil {
2122
return [][]int{}
@@ -57,3 +58,26 @@ func zigzagLevelOrder(root *TreeNode) [][]int {
5758
}
5859
return res
5960
}
61+
62+
// 解法二 递归
63+
func zigzagLevelOrder0(root *TreeNode) [][]int {
64+
var res [][]int
65+
search(root, 0, &res)
66+
return res
67+
}
68+
69+
func search(root *TreeNode, depth int, res *[][]int) {
70+
if root == nil {
71+
return
72+
}
73+
for len(*res) < depth+1 {
74+
*res = append(*res, []int{})
75+
}
76+
if depth%2 == 0 {
77+
(*res)[depth] = append((*res)[depth], root.Val)
78+
} else {
79+
(*res)[depth] = append([]int{root.Val}, (*res)[depth]...)
80+
}
81+
search(root.Left, depth+1, res)
82+
search(root.Right, depth+1, res)
83+
}

website/content/ChapterFour/0103.Binary-Tree-Zigzag-Level-Order-Traversal.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,8 @@ package leetcode
5656
* Right *TreeNode
5757
* }
5858
*/
59+
60+
// 解法一
5961
func zigzagLevelOrder(root *TreeNode) [][]int {
6062
if root == nil {
6163
return [][]int{}
@@ -98,4 +100,27 @@ func zigzagLevelOrder(root *TreeNode) [][]int {
98100
return res
99101
}
100102

103+
// 解法二 递归
104+
func zigzagLevelOrder0(root *TreeNode) [][]int {
105+
var res [][]int
106+
search(root, 0, &res)
107+
return res
108+
}
109+
110+
func search(root *TreeNode, depth int, res *[][]int) {
111+
if root == nil {
112+
return
113+
}
114+
for len(*res) < depth+1 {
115+
*res = append(*res, []int{})
116+
}
117+
if depth%2 == 0 {
118+
(*res)[depth] = append((*res)[depth], root.Val)
119+
} else {
120+
(*res)[depth] = append([]int{root.Val}, (*res)[depth]...)
121+
}
122+
search(root.Left, depth+1, res)
123+
search(root.Right, depth+1, res)
124+
}
125+
101126
```

0 commit comments

Comments
 (0)