# JS实现树的深度优先搜索和广度优先搜索

## 代码实现树的深度优先搜索

``````function Node(value) {
this.value = value;
this.childs = [];
}

var a = new Node("a");
var b = new Node("b");
var c = new Node("c");
var d = new Node("d");
var e = new Node("e");
var f = new Node("f");

a.childs.push(c);
a.childs.push(f);
a.childs.push(b);
b.childs.push(d);
b.childs.push(e);

function deepSearch(root, target) {
if (root == null) return false;
if (root.value == target) return true;
var result = false;
for (var i = 0 ; i < root.childs.length ; i ++) {
result |= deepSearch(root.childs[i], target);
}
return result ? true : false;
}

console.log(deepSearch(a, "e"));

### 代码实现树的广度优先搜索

``````function Node(value) {
this.value = value;
this.childList = [];
}

var a = new Node("a");
var b = new Node("b");
var c = new Node("c");
var d = new Node("d");
var e = new Node("e");
var f = new Node("f");

a.childList.push(c);
a.childList.push(f);
a.childList.push(b);
b.childList.push(d);
b.childList.push(e);

function f1(rootList,target){
if (rootList == null || rootList.length == 0) return false;
var childList = [];//当前层所有节点的子节点，都在这个list中，这样传入下一层级的时候，就可以遍历整个层级的节点。
for (var i = 0; i < rootList.length; i++) {
if (rootList[i] !== null && rootList[i].value == target) {
return true;
} else {
childList = childList.concat(rootList[i].childList);
}
}
return f1(childList,target);
}
console.log(f1([a],'e'));