zl程序教程

您现在的位置是:首页 >  后端

当前栏目

二叉树的建立和输出 (层序和递归两种)

二叉树输出递归 建立 两种 层序
2023-09-14 08:56:53 时间
func main() {
    //按数组层序建立二叉树,之后层序输出二叉树
    root:=createTree(0,[]int{1,2,3,4,5,6})
    ans:=printTree(root)
    fmt.Println(ans)
    
    //先序建立二叉树,之后先序输出二叉树
    var tmp *TreeNode
    for i:=0;i<6;i++{
        tmp=insert(tmp,i)
    }
    print(tmp)
}
type TreeNode struct {
    Val int
    Left *TreeNode
    Right *TreeNode
}
// 按数组建立二叉树
func createTree(index int,nums []int) *TreeNode{
    if index>=len(nums){
        return nil
    }
    root:=&TreeNode{
        Val:   nums[index],
    }
    root.Left=createTree(index*2+1,nums)
    root.Right=createTree(index*2+2,nums)
    return root
}

// 二叉树的层序遍历
func printTree(root *TreeNode) [][]int{
    que:=make([]*TreeNode,0)
    que=append(que,root)
    ans:=make([][]int,0)
    if root==nil{
        return ans
    }
    for len(que)!=0{
        size:=len(que)
        ans2:=make([]int,0)
        for i:=0;i<size;i++{
            front:=que[0]
            ans2=append(ans2,front.Val)
            que=que[1:]
            if front.Left!=nil{
                que=append(que,front.Left)
            }
            if front.Right!=nil{
                que=append(que,front.Right)
            }
        }
        ans=append(ans,ans2)
    }
    return ans
}
//先序建立二叉树
func insert(root *TreeNode,x int) *TreeNode{
    if root==nil{
        tmp:=&TreeNode{
            Val:x,
        }
        return tmp
    }
    if x<=root.Val{//这里是按照先序遍历的方式建立二叉树
        root.Left=insert(root.Left,x)
    }else{
        root.Right=insert(root.Right,x)
    }
    return root
}
//二叉树的先序遍历
func print(root *TreeNode){
    if root==nil{
        return
    }
    fmt.Printf("%v ",root.Val)
    if root.Left!=nil{
        print(root.Left)
    }
    if root.Right!=nil{
        print(root.Right)
    }
}