• 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
    }
    
    
  • 相关阅读:
    工作总结
    JSON数据使用
    DataTable知识
    树形结构菜单
    区域树前后台
    跨域总结
    工作一年感想
    项目整体架构分析
    springboot 和 mongdb连接问题 Exception in thread "main" com.mongodb.MongoSecurityException:
    go函数、方法、接口笔记
  • 原文地址:https://www.cnblogs.com/xdao/p/go_deep.html
Copyright © 2020-2023  润新知