github.com/searKing/golang/go@v1.2.117/container/traversal/node.go (about)

     1  // Copyright 2020 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package traversal
     6  
     7  type LeftNodes interface {
     8  	// Left returns the left node list or nil.
     9  	LeftNodes() []any
    10  }
    11  
    12  type MiddleNodes interface {
    13  	// Middle returns the middle node list or nil.
    14  	MiddleNodes() []any
    15  }
    16  
    17  type RightNodes interface {
    18  	// Right returns the middle node list or nil.
    19  	RightNodes() []any
    20  }
    21  
    22  // a uniform node
    23  type Node interface {
    24  	LeftNodes
    25  	MiddleNodes
    26  	RightNodes
    27  }
    28  
    29  // levelNode represents a single node with depth found in a structure.
    30  type levelNode struct {
    31  	node    any
    32  	depth   int
    33  	visited bool
    34  }
    35  
    36  func (n *levelNode) leftLevelNodes() []levelNode {
    37  	var lefts []levelNode
    38  	for _, node := range n.leftNodes() {
    39  		ln := levelNode{
    40  			node:  node,
    41  			depth: n.depth + 1,
    42  		}
    43  		lefts = append(lefts, ln)
    44  	}
    45  	return lefts
    46  }
    47  
    48  func (n *levelNode) middleLevelNodes() []levelNode {
    49  	var middles []levelNode
    50  	for _, node := range n.middleNodes() {
    51  		ln := levelNode{
    52  			node:  node,
    53  			depth: n.depth + 1,
    54  		}
    55  		middles = append(middles, ln)
    56  	}
    57  	return middles
    58  }
    59  
    60  func (n *levelNode) rightLevelNodes() []levelNode {
    61  	var rights []levelNode
    62  	for _, node := range n.rightNodes() {
    63  		ln := levelNode{
    64  			node:  node,
    65  			depth: n.depth + 1,
    66  		}
    67  		rights = append(rights, ln)
    68  	}
    69  	return rights
    70  }
    71  
    72  // children
    73  func (n *levelNode) leftNodes() []any {
    74  	if n.node == nil {
    75  		return nil
    76  	}
    77  	left, ok := n.node.(LeftNodes)
    78  	if ok {
    79  		return left.LeftNodes()
    80  	}
    81  	return nil
    82  }
    83  
    84  func (n *levelNode) middleNodes() []any {
    85  	if n.node == nil {
    86  		return nil
    87  	}
    88  	middle, ok := n.node.(MiddleNodes)
    89  	if ok {
    90  		return middle.MiddleNodes()
    91  	}
    92  	return nil
    93  
    94  }
    95  
    96  func (n *levelNode) rightNodes() []any {
    97  	if n.node == nil {
    98  		return nil
    99  	}
   100  	right, ok := n.node.(RightNodes)
   101  	if ok {
   102  		return right.RightNodes()
   103  	}
   104  	return nil
   105  
   106  }