golang深度获取子节点

起因

需要在树形结构里获取子树,树形结构一般是存储一维数组,数组元素里存储子节点的指针

代码

package main

import (
	"errors"
	"fmt"
)

type Node struct {
	Deep  int
	Child *Node
}

func (n *Node) GetChild() *Node {
	return n.Child
}

func (n *Node) SetChild(child *Node) {
	n.Child = child
}

func GetDeepChild(node *Node, level int) (*Node, error) {
	if level < 0 {
		return nil, errors.New("level must >= 0")
	}
	if level == 0 {
		return node, nil
	} else {
		child := node.GetChild()
		if child == nil {
			return nil, nil
		}
		return GetDeepChild(child, level-1)
	}

}

func main() {
	root := &Node{Deep: 0}
	child1 := &Node{Deep: 1}
	root.SetChild(child1)

	child2 := &Node{Deep: 2}
	child1.SetChild(child2)

	child3 := &Node{Deep: 3}
	child2.SetChild(child3)

	child4 := &Node{Deep: 4}
	child3.SetChild(child4)

	child, _ := GetDeepChild(root, 3)
	fmt.Printf("child %#v\n", child) // deep 3
	child, _ = GetDeepChild(root, 5)
	fmt.Printf("child %#v\n", child) // nil
}

posted @ 2018-05-16 19:27  半山th  阅读(784)  评论(0编辑  收藏  举报