Go遍历二叉树

package main
  
import "fmt"

type Node struct {
    Val   int
    Left  *Node
    Right *Node
}

//       1
//     /   \
//    2     3
//   / \   / \
//  4   5 6   7
func main() {
    head := &Node{1, nil, nil}
    head.Left = &Node{2, nil, nil}
    head.Right = &Node{3, nil, nil}
    head.Left.Left = &Node{4, nil, nil}
    head.Left.Right = &Node{5, nil, nil}
    head.Right.Left = &Node{6, nil, nil}
    head.Right.Right = &Node{7, nil, nil}
    printBinaryTree(head)  // 1 2 3 4 5 6 7
    printBinaryTree2(head) // 1 2 4 5 3 6 7
}

func printBinaryTree(root *Node) {
    if root == nil {
        return
    }
    cur := []*Node{root}
    // res := []int{}
    for len(cur) != 0 {
        next := []*Node{}
        for _, node := range cur {
            fmt.Println(node.Val)
            // res = append(res, node.Val)
            if node.Left != nil {
                next = append(next, node.Left)
            }
            if node.Right != nil {
                next = append(next, node.Right)
            }
        }
        cur = next
    }
}

func printBinaryTree2(root *Node) {
    if root == nil {
        return
    }
    fmt.Println(root.Val)
    if root.Left != nil {
        printBinaryTree2(root.Left)
    }
    if root.Right != nil {
        printBinaryTree2(root.Right)
    }
}
发布了162 篇原创文章 · 获赞 131 · 访问量 83万+

猜你喜欢

转载自blog.csdn.net/u013474436/article/details/105392490