簡體   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