zoukankan      html  css  js  c++  java
  • 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)
    }

    运行结果:

  • 相关阅读:
    SpringFlex框架搭建
    SqlDataReader的用法 转自https://www.cnblogs.com/sunxi/p/3924954.html
    C#学习笔记:ListBox控件的用法
    C#栈Stack的使用
    C# 队列Queue
    xshell传送文件
    Java基础中字符串与字符的注意点!
    大数据的基础学习:
    Python的空行
    Python基本语法
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12029805.html
Copyright © 2011-2022 走看看