問題:
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.
For example:
Given the below binary tree and sum = 22,
image.png
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
大意:
給出一個二叉樹和一個值,判斷樹是否有從根節(jié)點到葉子節(jié)點的路徑讓每個節(jié)點的值加起來等于給出的值。
例子:
給出下面的二叉樹以及 sum = 22,
image.png
返回true,因為存在根節(jié)點到葉子節(jié)點的路徑 5->4->11->2 加起來的和為22。
思路:
這個因為只需要判斷有沒有路徑滿足,也就是說只需要找到一條即可,那么采用深度優(yōu)先遍歷比較好,用遞歸來實現(xiàn)。
每次判斷當前路徑的累加和是否等于目標值了,如果等于,因為題目要求從根節(jié)點到葉子節(jié)點,所以還要判斷是否已經(jīng)到葉子節(jié)點了,這個對有無左右子節(jié)點判斷就可以了。
如果還不等于,那么就繼續(xù)判斷走左子節(jié)點或者走右子節(jié)點有沒有等于。
要注意的是題目并沒說節(jié)點值都是正數(shù),我之前對當前的累加和是否已經(jīng)大于了目標值來希望減少一些多余的運算,屬于自作聰明了,對于負數(shù)目標值來說,就完全錯誤了。
代碼(Java):
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
return canSum(root, sum, 0);
}
public boolean canSum(TreeNode root, int sum, int nowSum) {
if (root == null) return false;
nowSum = nowSum + root.val;
System.out.println(nowSum);
if (nowSum == sum && root.left == null && root.right == null) return true;
else return canSum(root.left, sum, nowSum) || canSum(root.right, sum, nowSum);
}
}
合集:https://github.com/Cloudox/LeetCode-Record

