代码实现二叉树的深搜和广搜

阅读 33

2022-03-17

深搜

在这里插入图片描述

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;
c.left = f;
c.right = g;
b.left = d;
b.right = e;

// 对于二叉树来说,深度优先搜索,和前序遍历的顺序是一样的。
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, "f"));

广搜

在这里插入图片描述

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;
c.left = f;
c.right = g;
b.left = d;
b.right = 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.push(rootList[i].left);   // 打印当前节点的左子树
            childList.push(rootList[i].right);  // 打印当前节点的右子树
        }
    }
    // console.log(childList)   // 打印这个节点集合
    return f1(childList, target);   
}
console.log(f1([a],'e'))

精彩评论(0)

0 0 举报