好像还没人写过ts版本的题解,我就先来抛砖引玉了(笑)。
思路其实很简单,就是在前序遍历的过程中,记录当前结点为止的结点值之和,这样到叶结点的时候就可以很容易地判断路径总和是否等于目标值了。
因为用的是迭代,不像递归那么直接就可以处理前缀和,所以干脆用一个Map来存储了。
function hasPathSum(root: TreeNode | null, sum: number): boolean {
if (!root) return false;
const stack = [root];
const pre_sum = new Map<TreeNode, number>();
pre_sum.set(root, root.val);
while (stack.length) {
const top = stack.pop()!;
const top_val = pre_sum.get(top)!;
if (!top.left && !top.right && top_val === sum) return true;
if (top.left) {
pre_sum.set(top.left, top_val + top.left.val);
stack.push(top.left);
}
if (top.right) {
pre_sum.set(top.right, top_val + top.right.val);
stack.push(top.right);
}
}
return false;
}
可能需要注意的地方:
- 适当使用非空断言(或者类型守卫,再或者是一些控制流,这个就看个人喜好了)。因为题目的类型定义,结点的类型是
TreeNode | null
,如果不加非空断言就会报错TS2531: Object is possibly 'null'
。 - 从Map里取值时有可能出现
undefined
。这个和第一个的性质其实是一样的,都是确保非空。