ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## 二叉树中和为某一值的路径 输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前) 前序遍历 + 递归 ``` var path = []; var stack = []; function FindPath(root, expectNumber) { if (root == null) return []; stack = []; path = []; cal(root, expectNumber); return path; } function cal(root, expectNumber) { stack.push(root.val); if (root.val == expectNumber && root.left == null && root.right == null) { path.push(stack.slice()); } else { if (root.left != null) { cal(root.left, expectNumber - root.val); } if (root.right != null) { cal(root.right, expectNumber - root.val); } } stack.pop(); /*这一步很关键,把所有push进去的每一个元素在递归执行完成之时都弹出来,使得stack每次都是重头来过。。*/ } ```