这是树的深度优先搜索并不是二叉树的深度优先搜索
实现源码
class Node {
constructor(value) {
this.value = value;
this.child = [];
}
}
const A = new Node('A')
const B = new Node('B')
const C = new Node('C')
const D = new Node('D')
const E = new Node('E')
const F = new Node('F')
A.child.push(C)
A.child.push(F)
A.child.push(B)
B.child.push(D)
B.child.push(E)
/**
* 树的深度优先搜索
* @param {*} root 节点
*/
function deepNode(root) {
if (root == null) return
console.log(root.value)
for (let i = 0; i < root.child.length; i++) {
let newRoot = root.child[i]
deepNode(newRoot)
}
}
deepNode(A)
打印结果
最终的代码
class node {
constructor(value) {
this.value = value;
this.child = [];
}
}
const a = new node('a');
const c = new node('c');
const f = new node('f');
const b = new node('b');
const d = new node('d');
const e = new node('e');
a.child.push(c);
a.child.push(f);
a.child.push(b);
b.child.push(d);
b.child.push(e);
/**
* 树的深度优先搜索
* @param {*} root
* @param {*} target
* @returns
*/
function deepSearch(root,target) {
if(root == null) return false;
if(root.value == target) return true;
let result = false;
for(let i = 0; i < root.child.length; i++) {
result = deepSearch(root.child[i], target);
}
return result
}
console.log(deepSearch(a, 'e'))