常见递归算法

由于在工作中经常碰到 数组里面的对象有个属性children又是数组,现在记录下来常见递归算法
对象结构
常见递归算法_第1张图片

根据code递归找到对象

List<OuNode> roots = new ArrayList<>();
private OuNode findNode(String code) {
        for (OuNode root : roots) {
            OuNode node = findNodeRec(code, root);
            if(node != null) {
                return node;
            }
        }
        return null;
    }

 private OuNode findNodeRec(String code, OuNode node) {
     if(node.getCode().equals(code)) {
         return node;
     } else {
         for (OuNode child : node.getChildren()) {
             OuNode childNode = findNodeRec(code, child);
             if(childNode != null) {
                 return childNode;
             }
         }
         return null;
     }
 }

从多叉树中取对象的某个属性放到数组返回

 getGridAndChildId(currNode: SelectTreeNode<PatrolGridProperty> | null){
    let ids:number[] = []
    if(currNode != null){
     ids.push(parseInt(currNode.key))
     this.filleGridChildrenIds(ids, currNode.children)
    }
    return ids
  }


  filleGridChildrenIds(ids: number[], gridTree: SelectTreeNode<PatrolGridProperty>[]){
    gridTree.forEach(node => {
      if (node.children == null || node.children.length == 0) {
        ids.push(parseInt(node.key));
      } else {
        this.filleGridChildrenIds(ids, node.children);
      }
    })
  }

你可能感兴趣的:(java,算法)