1️⃣ 深度优先搜索
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');var h = new Node('h');var i = new Node('i');var j = new Node('j');var k = new Node('k');a.left = b;a.right = c;b.left = d;b.right = e;c.left = f;c.right = g;d.left = h;d.right = i;g.left = j;g.right = k;// 对于二叉树来说,深度优先搜索和前序遍历的顺序是一样的。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, 'i'));
1️⃣ 广度优先搜索
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');var h = new Node('h');var i = new Node('i');var j = new Node('j');var k = new Node('k');a.left = b;a.right = c;b.left = d;b.right = e;c.left = f;c.right = g;d.left = h;d.right = i;g.left = j;g.right = k;function fun(rootList, target) { if (rootList == null || rootList.length == 0) return false; var 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); } } console.log(childList); return fun(childList, target);}console.log(fun([a], 'i'));