• golang数据结构之树的三种遍历方式


    tree.go

    package tree
    
    import (
        "fmt"
    )
    
    type TreeNode struct {
        ID    int
        Val   int
        Left  *TreeNode
        Right *TreeNode
    }
    
    func PreOrder(root *TreeNode) {
        if root != nil {
            fmt.Printf("%d ", root.Val)
            PreOrder(root.Left)
            PreOrder(root.Right)
        }
    }
    
    func InOrder(root *TreeNode) {
        if root != nil {
            InOrder(root.Left)
            fmt.Printf("%d ", root.Val)
            InOrder(root.Right)
        }
    }
    
    func PostOrder(root *TreeNode) {
        if root != nil {
            PostOrder(root.Left)
            PostOrder(root.Right)
            fmt.Printf("%d ", root.Val)
        }
    }

    main.go

    package main
    
    import (
        "fmt"
        "go_code/data_structure/tree"
    )
    
    func main() {
    
        node7 := &tree.TreeNode{
            ID:    7,
            Val:   7,
            Left:  nil,
            Right: nil,
        }
        node6 := &tree.TreeNode{
            ID:    6,
            Val:   6,
            Left:  nil,
            Right: nil,
        }
        node5 := &tree.TreeNode{
            ID:    5,
            Val:   5,
            Left:  nil,
            Right: nil,
        }
        node4 := &tree.TreeNode{
            ID:    4,
            Val:   4,
            Left:  nil,
            Right: nil,
        }
        node3 := &tree.TreeNode{
            ID:    3,
            Val:   3,
            Left:  node6,
            Right: node7,
        }
        node2 := &tree.TreeNode{
            ID:    2,
            Val:   2,
            Left:  node4,
            Right: node5,
        }
    
        node1 := &tree.TreeNode{
            ID:    1,
            Val:   1,
            Left:  node2,
            Right: node3,
        }
    
        fmt.Println("先序遍历")
        tree.PreOrder(node1)
        fmt.Println()
        fmt.Println("中序遍历")
        tree.InOrder(node1)
        fmt.Println()
        fmt.Println("后序遍历")
        tree.PostOrder(node1)
    }

    运行结果:

  • 相关阅读:
    docker on spark
    Install Docker Mac OS X
    HBase 1.1.1 发布(分布式数据库)
    spark streaming原理
    spark RDD的原理
    spark implementation hadoop setup,cleanup
    最近hadoop遇到的issuses
    Spark的日志配置
    大数据系列修炼-Scala课程11
    大数据系列修炼-Scala课程10
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12029805.html
Copyright © 2020-2023  润新知