题目描述

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径

 

题目分析

这题基本上一看就知道应该深度遍历整个树,并且把已经走过的节点的和与期望值作比较就行,如果走到底还不符合要求的话,就要回退值。

 

代码

function FindPath(root, expectNumber) {
  // write code here
  const list = [],
    listAll = [];
  return findpath(root, expectNumber, list, listAll);
}
function findpath(root, expectNumber, list, listAll) {
  if (root === null) {
    return listAll;
  }
  list.push(root.val);
  const x = expectNumber - root.val;
  if (root.left === null && root.right === null && x === 0) {
    listAll.push(Array.of(...list));
  }
  findpath(root.left, x, list, listAll);
  findpath(root.right, x, list, listAll);
  list.pop();
  return listAll;
}

 

  

相关文章:

  • 2021-12-05
  • 2021-10-22
  • 2021-04-24
  • 2021-10-19
  • 2021-07-24
  • 2021-08-12
  • 2022-12-23
猜你喜欢
  • 2021-06-11
  • 2022-12-23
  • 2022-02-12
  • 2022-12-23
  • 2021-10-09
  • 2021-10-13
  • 2021-06-08
相关资源
相似解决方案