一、深度优先搜索
function Tree(value) {
this.value = value;
this.left = null;
this.right = null;
}
const a = new Tree("A");
const b = new Tree("B");
const c = new Tree("C");
const d = new Tree("D");
const e = new Tree("E");
const f = new Tree("F");
const g = new Tree("G");
a.left = b;
a.right = c;
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;
let left = deepSearch(root.left, target);
let right = deepSearch(root.right, target);
return left || right;
}
console.log(deepSearch(a, 'E'))
二、广度优先搜索
function wideSearch(rootList, target) {
if(rootList == null) return false;
let childList = [];
for(let 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 wideSearch(childList, target);
}
console.log(wideSearch([a], 'E'))
深度优先搜索,先遍历左子树,再遍历右子树
广度优先搜索,相当于直接横向打印二叉树
深度优先搜索使用栈,先进后出
广度优先搜索使用队列,先进先出