【Leetcode】【DFS】 112. Path Sum / 路經總和
阿新 • • 發佈:2018-11-10
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \\ 7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
簡單使用DFS來遍歷。
首先,判斷true的條件是走到了葉子,且路徑值為sum。判斷false的條件是走到了空節點(即超出了葉子都沒能滿足true,說明這條路徑不符合)。
在每一步,sum都減去該節點的val。所以判斷路徑和等於sum即等於判斷當前的sum是否為0。
在最開始做的時候試圖判斷sum是否小於0來提前退出而避免不必要的遍歷。然而節點值是有正有負的,不能簡單的這麼判斷。
總程式碼:
bool hasPathSum(TreeNode* root, int sum) { if(root == nullptr) return false; sum -= root->val; if(sum == 0 && root->left == nullptr && root->right == nullptr) return true; bool left = hasPathSum(root->left, sum); bool right = hasPathSum(root->right, sum); return left || right; }