• 两种语言实现的树结构


    golang

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"go_study3/sql"
    	"strconv"
    	"strings"
    )
    
    /**
    将一条记录添加到树
    */
    
    type treeNode struct {
    	Name     string
    	Id       string
    	IsTeam   bool
    	Children *[]treeNode
    	Position string
    }
    
    // result是一个列表,每个item是一个字典,如果 team = 字典["Name"] 则返回这个item
    func getChildrenByTeam(team string, result *[]treeNode) *[]treeNode {
    	for _, v := range *result {
    		if team == v.Name {
    			return v.Children
    		}
    	}
    	fmt.Println("执行到这里了")
    	return nil
    }
    
    func getTeamInChildren(team string, children *[]treeNode) *treeNode {
    	for _, child := range *children {
    		if team == child.Name {
    			return &child
    		}
    	}
    	return nil
    }
    
    func getChildren(teams []string, i int, result *[]treeNode) *[]treeNode {
    	tmp := result
    	tmpTeams := teams[:i]
    	for _, team := range tmpTeams {
    		tmp = getChildrenByTeam(team, tmp)
    	}
    	return tmp
    }
    
    func addOneItem(user sql.User, result *[]treeNode) {
    	// 出现异常了恢复
    	defer func() {
    		err := recover()
    		if err != nil {
    			fmt.Println("ERROR,内容如下", user, err)
    		}
    	}()
    
    	position := user.Position
    	teams := strings.Split(strings.Trim(position, "/"), "/")
    
    	children := new([]treeNode)
    	teamStruct := new(treeNode)
    	count := 0
    
    	for i, team := range teams {
    		if i == 0 {
    			children = result
    		} else {
    			children = getChildren(teams, i, result)
    		}
    
    		teamStruct = getTeamInChildren(team, children) // team对象 的指针
    
    		if teamStruct == nil {
    			tmp := treeNode{
    				Name:     team,
    				IsTeam:   true,
    				Id:       strconv.Itoa(count),
    				Children: new([]treeNode),
    			}
    			teamStruct = &tmp
    			*children = append(*children, tmp)
    			count++
    
    			//fmt.Println(children)
    			//fmt.Println(result)
    		}
    	}
    	node := treeNode{
    		Name:     user.Username,
    		Id:       user.Id,
    		IsTeam:   false,
    		Children: nil,
    		Position: user.Position,
    	}
    
    	*teamStruct.Children = append(*teamStruct.Children, node)
    }
    
    func main() {
    	fmt.Println("hello")
    
    	users := sql.QueryMultiRowDemo2(3000)
    
    	result := make([]treeNode, 0)
    	fmt.Printf("result = %p
    ", result)
    	for _, user := range users {
    		fmt.Println(user)
    		if user.Position != "" {
    			addOneItem(user, &result)
    		}
    	}
    	fmt.Println(result)
    
    	strByte, err := json.Marshal(result)
    	if err != nil {
    		fmt.Println("err", err)
    	} else {
    		strJson := string(strByte)
    		fmt.Println(strJson)
    	}
    
    }
    

      python

    """
        Created by yang on 2020/10/14
        dim 用户-树形结构
    """
    import json
    
    from test01.dbUtils import MysqlConn
    
    
    def get_children_by_team(team, result):
        """
        result是一个列表,每个item是一个字典,如果 team = 字典["name"] 则返回这个item
        :return:
        """
        for item in result:
            if team == item["name"]:
                return item["children"]
    
    
    def team_in_children(team, children):
        for item in children:
            if team == item["name"]:
                return True
        return False
    
    
    def get_children(teams: list, i: int, result: list):
        """
        寻找最内层的children  是一个list
        :param teams:
        :param i:
        :param result:
        :return:
        """
        tmp = result
        tmp_teams = teams[:i]
        for team in tmp_teams:
            tmp = get_children_by_team(team, tmp)
        return tmp
    
    
    id = 0
    
    
    def add_one_item(item, result: list):
        """
        将一条记录添加到树
        :param item:
        :param result:
        :return:
        """
        if not item["Position"]:
            return
        position = item["Position"]
        print(position)
        teams = position.strip("/").split("/")
        global id
        children = []
        for i, team in enumerate(teams):
            if i == 0:
                children = result
            else:
                children = get_children(teams, i, result)
    
            if not team_in_children(team, children):
                tmp = {
                    "name": team,
                    "is_team": True,
                    "id": id,
                    "children": []
                }
                children.append(tmp)
                id += 1
    
        item["id"] = item.pop("Id")
        item["name"] = item.pop("Nickname")
        item["is_team"] = False
    
        children[-1]["children"].append(item)
    
    
    def f1():
        conn = MysqlConn("200.200.84.30", "mmuser", "mostest")
        res = conn.execSql("select Id,Nickname,Position from `mattermost_test`.`Users` limit 10")
        result = []
        for item in res:
            add_one_item(item, result)
        print(json.dumps(result, indent=4, ensure_ascii=False))
    
    
    if __name__ == '__main__':
        f1()
    

      树结构

    [
        {
            "name": "",
            "is_team": true,
            "id": 0,
            "children": [
                {
                    "name": "",
                    "is_team": true,
                    "id": 1,
                    "children": [
                        {
                            "name": "",
                            "is_team": true,
                            "id": 2,
                            "children": [
                                {
                                    "name": "",
                                    "is_team": true,
                                    "id": 3,
                                    "children": [
                                        {
                                            "name": "",
                                            "is_team": true,
                                            "id": 4,
                                            "children": [
                                                {
                                                    "Position": "",
                                                    "id": "",
                                                    "name": "",
                                                    "is_team": false
                                                }
                                            ]
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            "name": "",
                            "is_team": true,
                            "id": 15,
                            "children": [
                                {
                                    "name": "",
                                    "is_team": true,
                                    "id": 16,
                                    "children": [
                                        {
                                            "name": "",
                                            "is_team": true,
                                            "id": 17,
                                            "children": [
                                                {
                                                    "Position": "",
                                                    "id": "",
                                                    "name": "",
                                                    "is_team": false
                                                }
                                            ]
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                },
                {
                    "name": "",
                    "is_team": true,
                    "id": 5,
                    "children": [
                        {
                            "name": "",
                            "is_team": true,
                            "id": 6,
                            "children": [
                                {
                                    "name": "",
                                    "is_team": true,
                                    "id": 7,
                                    "children": [
                                        {
                                            "Position": "",
                                            "id": "",
                                            "name": "",
                                            "is_team": false
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        },
        {
            "name": "公司2",
            "is_team": true,
            "id": 8,
            "children": [
                {
                    "name": "",
                    "is_team": true,
                    "id": 9,
                    "children": [
                        {
                            "name": "",
                            "is_team": true,
                            "id": 10,
                            "children": [
                                {
                     
    

      

  • 相关阅读:
    HTML基础(一)基本语法知识
    本地方法接口
    本地方法栈
    虚拟机栈相关的问题
    栈帧的内部结构--一些附加信息
    基于角色的权限控制设计
    SpringBoot普通消息队列线程池配置
    栈帧的内部结构--动态返回地址(Return Address)
    栈帧的内部结构--动态链接 (Dynamic Linking)
    栈帧的内部结构--操作数栈(Opreand Stack)
  • 原文地址:https://www.cnblogs.com/jec1999/p/13827303.html
Copyright © 2020-2023  润新知