繁体   English   中英

在二叉树中从根到节点的返回路径

[英]Return path from root to node in a binary tree

我正在尝试完成看似简单但难以实现的事情。 给定一棵二叉树和一个节点,返回路径。 我在下面尝试过,但是我真的被卡住了。 我也不太确定在找到目标节点后如何退出递归函数。

 const tree = { val: 3, left: { val: 5, left: { val: 6, left: null, right: null }, right: { val: 2, left: null, right: null } }, right: { val: 1, left: null, right: null } }; const findPathFromRoot = (currentNode, targetNode, path) => { path + currentNode.val; if (currentNode === targetNode) { return path + targetNode.val; } findPathFromRoot(currentNode.left, targetNode, path); findPathFromRoot(currentNode.right, targetNode, path); } const target = tree.left.right; console.log(findPathFromRoot(tree, target, '')); // should return "352" 

const findPathFromRoot = (root, target, path = "") => {
  if (root === null) {
    return null;
  }
  path = path + root.val;
  if (root === target) {
    return path;
  }

  const left = findPathFromRoot(root.left, target, path);
  const right = findPathFromRoot(root.right, target, path);

  return left || right;
};

为什么这样做?

Return语句始终返回到调用方,在您的情况下,仅当找到目标时才返回,而目标又返回到findPathFromRoot(currentNode.left,...)或findPathFromRoot(currentNode.right,... )。 但是这些不会自我回报。 因此,如果您在左侧或右侧子树中找到目标,则代码的修复方法是返回。

就像评论中提到的那样,如果对树进行排序,则可以使其更快。

照原样,每个节点都需要检查。

您的尝试几乎在那儿,首先您需要检查您是否有左节点或右节点,然后检查左节点,如果找到该树下方的节点将返回,如果没有,则尝试正确的节点。 它递归地执行此操作,以便访问每个可能的节点。

下面是一个工作示例。

 const tree = { val: 3, left: { val: 5, left: { val: 6, left: null, right: null }, right: { val: 2, left: null, right: null } }, right: { val: 1, left: null, right: null } }; const findPathFromRoot = (currentNode, targetNode, path) => { path += currentNode.val; if (currentNode === targetNode) { return path; } let ret = null; if (currentNode.left) ret = findPathFromRoot(currentNode.left, targetNode, path); if (currentNode.right && !ret) ret = findPathFromRoot(currentNode.right, targetNode, path); return ret; } const target = tree.left.right; console.log(findPathFromRoot(tree, target, '')); // should return "352" 

您需要放入逻辑来确定是从当前节点的值向左还是向右移动,并根据该逻辑用currentNode.left或currentNode.right调用您的方法。 然后,当您获得空值(这意味着目标在树中不存在)时返回,或者在currentNode.value ===目标时返回。

但是,树也有问题,根的左侧的所有值都必须大于根的值,并且根的右侧的所有值都必须较小,但是看起来左边的2根的值(其值为3)。

暂无
暂无

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

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