The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
cheng8984

请教一个树平铺的问题

  •  
  •   cheng8984 · Sep 1, 2020 · 2034 views
    This topic created in 2081 days ago, the information mentioned may be changed or developed.
    type Tree struct {
    Code string `json:"code"`
    Parent string `json:"code"`
    Child []*OrgTree `json:"child"`
    }

    type Flat struct {
    Code string
    Parent string
    Lv0Code string
    Lv1Code string
    Lv2Code string
    Lv3Code string
    Lv4Code string
    Lv5Code string
    }

    树的层级为 6,求平铺这颗树,得到一个[]Flat 切片,要求每一层的节点对应 Flat 里的 lv 层 Code,比如第二层的&Flat{Code:"test2",Parent:"root",lv0Code:"rootCode",lv1Code:"test2"}
    Supplement 1  ·  Sep 1, 2020
    补充一下 树写错了哈
    type Tree struct {
    Code string `json:"code"`
    Parent string `json:"code"`
    Child []*Tree `json:"child"`
    }



    第二层:&Flat{Code:"test2",Parent:"root",lv0Code:"rootCode",lv1Code:"test2"}
    第三层:&Flat{Code:"test3",Parent:"test2",lv0Code:"rootCode",lv1Code:"test2",lv2Code:"test3"}
    3 replies    2020-09-02 15:44:10 +08:00
    EscYezi
        1
    EscYezi  
       Sep 2, 2020 via iPhone
    简单一点的解法:把树分成层,根是第一层,根的子节点是第二层,依次类推,然后每一层进行遍历。
    cheng8984
        2
    cheng8984  
    OP
       Sep 2, 2020
    @EscYezi 是这样的,我写了 5 层遍历 把自己丑哭了,想想递归应该是更好的解法,但是想了半天 没想清楚怎么写这个递归
    mind3x
        3
    mind3x  
       Sep 2, 2020 via Android
    BFS 遍历,经典做法是用一个队列,不需要递归
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   950 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 52ms · UTC 20:08 · PVG 04:08 · LAX 13:08 · JFK 16:08
    ♥ Do have faith in what you're doing.