当前位置:网站首页>Binary tree traversal - middle order traversal (golang)

Binary tree traversal - middle order traversal (golang)

2022-07-05 01:43:00 potato

brief introduction

In the sequence traversal (LDR) It's a kind of binary tree traversal , It's also called middle root traversal 、 Middle preface travels around .

Definition

In a binary tree , Middle order traversal first traverses the left subtree , Then access the root node , Finally, traverse the right subtree . If the binary tree is empty, it will return to , otherwise :(1) The middle order traverses the left subtree (2) Access root (3) The middle order traverses the right subtree
 Please add a picture description
As shown in the figure, binary tree , Middle order traversal result :DBEAFC

Golang Realization

func (root *TreeNode) inorder()[]int{
    res:=[]int{}
    if root==nil{
        return res
    }
    stack:=[]*TreeNode{}
    for root!=nil || len(stack)!=0{
        if root!=nil{
            stack=append(stack,root)
            root=root.Lchild
        }else{
            root=stack[len(stack)-1]
            res=append(res,root.data)
            stack=stack[:len(stack)-1]
            root=root.Rchild
        }
    }
    return res
}
原网站

版权声明
本文为[potato]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141018459177.html

随机推荐