引數為二叉樹和一個整數,求所有和為該整數的路徑

LJ2016發表於2019-08-28

javascript 雖然與PHP不同,寫起簡單的演算法來也是簡單有趣
題目,引數為二叉樹和一個整數,求所有和為該整數的路徑

典型的回溯法運用

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

function find_path(root, value, path, paths)
{
    if(!root) return;
    path.push(root.value);
    if(root.value == value){
        console.log(path);
        paths.push([...path]);
    }

    find_path(root.left, value - root.value, path, paths);
    find_path(root.right, value - root.value, path, paths);
    path.pop(root.value);

    return paths;
}

function print_tree(root)
{
    let a = tree2array(root);
    console.log(a);
}

function tree2array(root, s = [])
{
    if(!root) return;
    tree2array(root.left, s);
    s.push(root.value);
    tree2array(root.right, s);
    return s;
}

let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.right.right = new Node(-1);

left = root.left;
left.left = new Node(4);
left.right = new Node(-1);
left.right.left = new Node(1);

// print_tree(root);

let paths = find_path(root, 3, [], []);
console.log(paths);
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章