Merge pull request #304 from yigenshutiao/master

add 3 types traversal and test of binary tree
This commit is contained in:
wangzheng0822 2019-05-09 08:45:55 +08:00 committed by GitHub
commit cc1fddf584
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 160 additions and 0 deletions

View File

@ -0,0 +1,66 @@
package binarytree
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func preOrderTraversal(root *TreeNode) []int {
if root == nil {
return nil
}
if root.Left == nil && root.Right == nil {
return []int{root.Val}
}
var stack []*TreeNode
var res []int
stack = append(stack, root)
for len(stack) != 0 {
e := stack[len(stack)-1]
stack = stack[:len(stack)-1]
res = append(res, e.Val)
if e.Right != nil {
stack = append(stack, e.Right)
}
if e.Left != nil {
stack = append(stack, e.Left)
}
}
return res
}
func inOrderTraversal(root *TreeNode) []int {
if root == nil {
return nil
}
if root.Left == nil && root.Right == nil {
return []int{root.Val}
}
res := inOrderTraversal(root.Left)
res = append(res, root.Val)
res = append(res, inOrderTraversal(root.Right)...)
return res
}
func postOrderTraversal(root *TreeNode) []int {
if root == nil {
return nil
}
var res []int
if root.Left != nil {
lres := postOrderTraversal(root.Left)
if len(lres) > 0 {
res = append(res, lres...)
}
}
if root.Right != nil {
rres := postOrderTraversal(root.Right)
if len(rres) > 0 {
res = append(res, rres...)
}
}
res = append(res, root.Val)
return res
}

View File

@ -0,0 +1,94 @@
package binarytree
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
var tcs = []struct {
pre, in, post []int
}{
{
[]int{1, 2, 3},
[]int{1, 3, 2},
[]int{3, 2, 1},
},
{
[]int{1, 2, 4, 5, 3, 6, 7},
[]int{4, 2, 5, 1, 6, 3, 7},
[]int{4, 5, 2, 6, 7, 3, 1},
},
// 可以有多个 testCase
}
func PreIn2Tree(pre, in []int) *TreeNode {
if len(pre) != len(in) {
panic("preIn2Tree 中两个切片的长度不相等")
}
if len(in) == 0 {
return nil
}
res := &TreeNode{
Val: pre[0],
}
if len(in) == 1 {
return res
}
idx := indexOf(res.Val, in)
res.Left = PreIn2Tree(pre[1:idx+1], in[:idx])
res.Right = PreIn2Tree(pre[idx+1:], in[idx+1:])
return res
}
func indexOf(val int, nums []int) int {
for i, v := range nums {
if v == val {
return i
}
}
return 0
}
func Test_preOrderTraversal(t *testing.T) {
ast := assert.New(t)
for _, tc := range tcs {
fmt.Printf("~~%v~~\n", tc)
root := PreIn2Tree(tc.pre, tc.in)
ast.Equal(tc.pre, preOrderTraversal(root), "输入:%v", tc)
}
}
func Test_inOrderTraversal(t *testing.T) {
ast := assert.New(t)
for _, tc := range tcs {
fmt.Printf("~~%v~~\n", tc)
root := PreIn2Tree(tc.pre, tc.in)
ast.Equal(tc.in, inOrderTraversal(root), "输入:%v", tc)
}
}
func Test_postOrderTraversal(t *testing.T) {
ast := assert.New(t)
for _, tc := range tcs {
fmt.Printf("~~%v~~\n", tc)
root := PreIn2Tree(tc.pre, tc.in)
ast.Equal(tc.post, postOrderTraversal(root), "输入:%v", tc)
}
}