Solved the issue #253

This commit is contained in:
t0ur1st
2022-09-05 12:41:28 +08:00
parent 5ec282a5c7
commit 2dcb43efa1
3 changed files with 107 additions and 17 deletions

View File

@ -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
}
// 解法二 递归

View File

@ -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")
}