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

1,856

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

``````function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}

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");
var g = new Node("g");

a.left = c;
a.right = b;
b.left = d;
b.right = e;
c.left = f;
c.right = g;

function deepSearch(root,target){
if (root == null) return false;
if (root.value == target) return true;

var left = deepSearch(root.left,target);
var right = deepSearch(root.right,target);
return left || right;
}
console.log(deepSearch(a,'d'));

``````

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

``````function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}

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");
var g = new Node("g");

a.left = c;
a.right = b;
b.left = d;
b.right = e;
c.left = f;
c.right = g;

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.push(rootList[i].left);
childList.push(rootList[i].right);
}
}
return f1(childList,target);
}
console.log(f1([a],'e'));
``````