zoukankan      html  css  js  c++  java
  • 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
    ", child) // deep 3
    	child, _ = GetDeepChild(root, 5)
    	fmt.Printf("child %#v
    ", child) // nil
    }
    
    
  • 相关阅读:
    oracle重命名数据库
    GridView分页的实现
    vb发post信息,非常简单,就一个函数
    第六周进度条
    软件工程作业
    进度条第五周
    四则运算设计03
    进度条03
    单元测试课堂作业
    个人作业02
  • 原文地址:https://www.cnblogs.com/xdao/p/go_deep.html
Copyright © 2011-2022 走看看