深入搜索树 - JS

时间:2018-01-30 03:59:11

标签: javascript recursion tree

我正在尝试使用遍历树的伪经典方法创建一个deepSearch方法,其中每个节点的值创建一个新树,其结果具有相同的结构并包含结果。

public class Student {
    private String name;
    private String id;
    private ArrayList<Course> listCourses = new ArrayList<>();
    ...

    // this is just a setter for listCourses field
    public void setListCourses(ArrayList<Course> listCourses) {
        this.listCourses = listCourses;
    }
}

现在这是我的功能。

For instance:
  var root1 = new Tree(1);
  var branch2 = root1.addChild(2);
  var branch3 = root1.addChild(3);
  var leaf4 = branch2.addChild(4);
  var leaf5 = branch2.addChild(5);
  var leaf6 = branch3.addChild(6);
  var leaf7 = branch3.addChild(7);
  var newTree = root1.deepSearch(function (value) {
    return value * 2;
  })

  newTree.value // 2
  newTree.children[0].value // 4
  newTree.children[1].value // 6
  newTree.children[0].children[1].value // 10
  newTree.children[1].children[1].value // 14
   root1.value // still 1

知道我在这里做错了什么吗?

1 个答案:

答案 0 :(得分:0)

以下是递归地图调用的示例:

class Tree {
  constructor(value) {
    this.value = value;
    this.children = [];
  }

  addChild(value) {
    var child = new Tree(value);
    this.children.push(child);
    return child;
  } 

  map(callback) {
    function mapNode(node, copy, callback) {
      for (let child of node.children)
        mapNode(child, copy.addChild(callback(child.value)), callback);
    }

    var copy = new Tree(callback(this.value));
    mapNode(this, copy, callback);
    return copy;
  }
}

  var root1 = new Tree(1);
  var branch2 = root1.addChild(2);
  var branch3 = root1.addChild(3);
  var leaf4 = branch2.addChild(4);
  var leaf5 = branch2.addChild(5);
  var leaf6 = branch3.addChild(6);
  var leaf7 = branch3.addChild(7);
  var newTree = root1.map(function (value) {
    return value * 2;
  })

console.log(
  newTree.value, // 2
  newTree.children[0].value, // 4
  newTree.children[1].value, // 6
  newTree.children[0].children[1].value, // 10
  newTree.children[1].children[1].value, // 14
   root1.value // still 1
)