【问题标题】:Find parent node in binary tree from value in javascript从javascript中的值查找二叉树中的父节点
【发布时间】:2020-07-08 15:14:25
【问题描述】:

我有以下树形结构:

class Binarytree {
  constructor(val) {
    this.val = val;
    this.left = null;
    this.right = null;
  }

  insertLeft(val) {
    this.left = val;
  }

  insertRight(val) {
    this.right = val;
  }
}

我正在尝试从节点值中查找父节点。我创建了以下函数:

const getParent = function(root, n, parent) {
  if (!root) return null;
  if (root.val === n) return parent;
  else {
    getParent(root.left, n, root);
    getParent(root.right, n, root);
  }
};

这是我的测试用例:

const tree = new BinaryTree(1);
const node2 = new BinaryTree(2);
const node3 = new BinaryTree(3);
const node4 = new BinaryTree(4);
const node5 = new BinaryTree(5);
node2.insertRight(node4);
node3.insertRight(node5);
tree.insertLeft(node2);
tree.insertRight(node3);

const test = getParent(tree, 4, tree);

它总是返回 null。

【问题讨论】:

    标签: javascript tree binary-tree


    【解决方案1】:

    您需要返回getParent 的嵌套调用。您可以将呼叫与 logical OR ||.

    class BinaryTree {
        constructor(val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }
    
        insertLeft(val) {
            this.left = val;
        }
    
        insertRight(val) {
            this.right = val;
        }
    }
    
    const getParent = function(root, n, parent) {
        if (!root) return null;
        if (root.val === n) return parent;
        // return and chain with logical OR
        return getParent(root.left, n, root) || getParent(root.right, n, root);
    }
    
    
    const tree = new BinaryTree(1);
    const node2 = new BinaryTree(2);
    const node3 = new BinaryTree(3);
    const node4 = new BinaryTree(4);
    const node5 = new BinaryTree(5);
    node2.insertRight(node4);
    node3.insertRight(node5);
    tree.insertLeft(node2);
    tree.insertRight(node3);
    
    const test = getParent(tree, 4, tree);
    console.log(test);

    【讨论】:

    • 谢谢!我需要返回第一个不为空的(左或右)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多