Go 이 진 트 리 및 상용 문제 형 구현

package main

import (
	"fmt"
)

type BtNode struct {
	data  int
	left  *BtNode
	right *BtNode
}

func main() {
	n1 := BtNode{1, nil, nil}
	n2 := BtNode{2, nil, nil}
	n3 := BtNode{3, nil, nil}
	n4 := BtNode{4, nil, nil}
	n5 := BtNode{5, nil, nil}
	n6 := BtNode{6, nil, nil}
	n7 := BtNode{7, nil, nil}
	n8 := BtNode{8, nil, nil}
	n9 := BtNode{9, nil, nil}
	n10 := BtNode{10, nil, nil}
	n11 := BtNode{11, nil, nil}
	n1.left = &n2
	n1.right = &n3
	n2.left = &n4
	n3.left = &n5
	n3.right = &n6
	n5.left = &n7
	n6.right = &n8
	n7.left = &n9
	n7.right = &n10
	n10.left = &n11

	fmt.Print("BSearch():")
	n1.BSearch()
	fmt.Println("GetMaxDepth():", n1.GetMaxDepth())
	fmt.Println("GetKDepthNode():", n1.GetKDepthNode(4))
	fmt.Println("GetAllNode():", n1.GetAllNode())
	fmt.Println("GetLeafNode():", n1.GetLeafNode())

	fmt.Println("=====================")
}

// Go math.Max()      float  
func GetMax(a int, b int) int {
	if a >= b {
		return a
	} else {
		return b
	}
}
func GetMin(a int, b int) int{
	// Go         
	if a > b {
		return b
	}
	return a
}

//           
func (root *BtNode) BSearch() {
	if root == nil {
		return
	}

	queue := []*BtNode{root}
	for len(queue) != 0 {
		node := queue[0]
		fmt.Printf("%d\t", node.data)
		if node.left != nil {
			queue = append(queue, node.left)
		}
		if node.right != nil {
			queue = append(queue, node.right)
		}
		queue = queue[1:]
	}
	fmt.Println()
}

//         
func (root *BtNode) GetMaxDepth() int {
	if root == nil {
		return 0
	}
	left := root.left.GetMaxDepth()
	right := root.right.GetMaxDepth()
	return GetMax(left, right) + 1
}

//       K     
func (root *BtNode) GetKDepthNode(k int) int {
	if root == nil || k < 1 {
		return 0
	}

	if k == 1 {
		return 1
	}
	left := root.left.GetKDepthNode(k - 1)
	right := root.right.GetKDepthNode(k - 1)
	return left + right
}

//           :              
func (root *BtNode) GetAllNode() int {
	if root == nil {
		return 0
	}

	left := root.left.GetAllNode()
	right := root.right.GetAllNode()
	return left + right + 1
}

//            :                 ,                
func (root *BtNode) GetLeafNode() int {
	if root == nil {
		return 0
	}

	if root.left == nil && root.right == nil {
		return 1
	}
	left := root.left.GetLeafNode()
	right := root.right.GetLeafNode()
	return left + right
}

좋은 웹페이지 즐겨찾기