mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-05 00:25:22 +08:00
Solved the issue #253
This commit is contained in:
@ -18,23 +18,21 @@ type TreeNode = structures.TreeNode
|
||||
|
||||
// 解法一 非递归
|
||||
func flatten(root *TreeNode) {
|
||||
list, cur := []int{}, &TreeNode{}
|
||||
preorder(root, &list)
|
||||
cur = root
|
||||
list := preorder(root)
|
||||
for i := 1; i < len(list); i++ {
|
||||
cur.Left = nil
|
||||
cur.Right = &TreeNode{Val: list[i], Left: nil, Right: nil}
|
||||
cur = cur.Right
|
||||
prev, cur := list[i-1], list[i]
|
||||
prev.Left, prev.Right = nil, cur
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func preorder(root *TreeNode, output *[]int) {
|
||||
func preorder(root *TreeNode) (ans []*TreeNode) {
|
||||
if root != nil {
|
||||
*output = append(*output, root.Val)
|
||||
preorder(root.Left, output)
|
||||
preorder(root.Right, output)
|
||||
ans = append(ans, root)
|
||||
ans = append(ans, preorder(root.Left)...)
|
||||
ans = append(ans, preorder(root.Right)...)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 解法二 递归
|
||||
|
@ -15,13 +15,13 @@ type question114 struct {
|
||||
// para 是参数
|
||||
// one 代表第一个参数
|
||||
type para114 struct {
|
||||
one []int
|
||||
one []string
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
// one 代表第一个答案
|
||||
type ans114 struct {
|
||||
one []int
|
||||
one []string
|
||||
}
|
||||
|
||||
func Test_Problem114(t *testing.T) {
|
||||
@ -29,8 +29,18 @@ func Test_Problem114(t *testing.T) {
|
||||
qs := []question114{
|
||||
|
||||
{
|
||||
para114{[]int{1, 2, 3, 4, 5, 6}},
|
||||
ans114{[]int{1, 2, 3, 4, 5, 6}},
|
||||
para114{[]string{"1", "2", "5", "3", "4", "null", "6"}},
|
||||
ans114{[]string{"1", "null", "2", "null", "3", "null", "4", "null", "5", "null", "6"}},
|
||||
},
|
||||
|
||||
{
|
||||
para114{[]string{"0"}},
|
||||
ans114{[]string{"0"}},
|
||||
},
|
||||
|
||||
{
|
||||
para114{[]string{"1", "2", "3", "4", "5", "6"}},
|
||||
ans114{[]string{"1", "2", "4", "5", "3", "6", "null"}},
|
||||
},
|
||||
}
|
||||
|
||||
@ -39,9 +49,10 @@ func Test_Problem114(t *testing.T) {
|
||||
for _, q := range qs {
|
||||
_, p := q.ans114, q.para114
|
||||
fmt.Printf("【input】:%v \n", p)
|
||||
rootOne := structures.Ints2TreeNode(p.one)
|
||||
rootOne := structures.Strings2TreeNode(p.one)
|
||||
flatten(rootOne)
|
||||
fmt.Printf("【output】:%v \n", structures.Tree2Preorder(rootOne))
|
||||
fmt.Printf("【levelorder output】:%v \n", structures.Tree2LevelOrderStrings(rootOne))
|
||||
fmt.Printf("【preorder output】:%v \n", structures.Tree2PreOrderStrings(rootOne))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
||||
|
Reference in New Issue
Block a user