二叉树之和为某一值得路径

题目

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

思路

遍历二叉树,判断值是否是目标值,不是则退回

代码

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

猜你喜欢

转载自blog.csdn.net/Gainsense/article/details/89075086
今日推荐