0
点赞
收藏
分享

微信扫一扫

Go 二叉树递归遍历输出(前序、中序、后序)

Go 二叉树递归遍历输出(前序、中序、后序)


  • 前序遍历:根结点 —> 左子树 —> 右子树
  • 中序遍历:左子树—> 根结点 —> 右子树
  • 后序遍历:左子树 —> 右子树 —> 根结点

树结构体
type TreeNode struct {
	Val 	int			//值
	Left 	*TreeNode	//左子树指针
	Right 	*TreeNode	//右子树指针
}

前序(深度优先遍历)
func kthLargest(root *TreeNode) {
    scan(root)
}

func scan(node *TreeNode) {

    if node == nil {
        return
    }
    
    fmt.Println(node.Val)	//输出节点值
    scan(node.Left)			//左子树递归
    scan(node.Right)		//右子树递归
}

中序
func kthLargest(root *TreeNode) {
    scan(root)
}

func scan(node *TreeNode) {

    if node == nil {
        return
    }
    
    scan(node.Left)			//左子树递归
    fmt.Println(node.Val)	//输出节点值
    scan(node.Right)		//右子树递归
}

后序
func kthLargest(root *TreeNode) {
    scan(root)
}

func scan(node *TreeNode) {

    if node == nil {
        return
    }
   	
    scan(node.Left)			//左子树递归
    scan(node.Right)		//右子树递归
    fmt.Println(node.Val)	//输出节点值
}
举报

相关推荐

0 条评论