简体   繁体   English

从 javascript 中的值查找二叉树中的父节点

[英]Find parent node in binary tree from value in javascript

I have the following tree structure:我有以下树结构:

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

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

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

I'm trying to find a parent node from a node value.我正在尝试从节点值中找到父节点。 I created the function below:我在下面创建了 function:

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);
  }
};

Here is my test case:这是我的测试用例:

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);

It is always returning null.它总是返回 null。

You need to return the nested call of getParent .您需要返回getParent的嵌套调用。 You could chain the calls with logical OR ||您可以使用逻辑 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM