好像還沒人寫過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
。這個和第一個的性質其實是一樣的,都是確保非空。