public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
int tmp = 0;
return helper(root, tmp, sum);
}
// inorder traversing
public static boolean helper(TreeNode t, int tmp, int sum) {
if (t == null) return false;
// found a leaf node
if (t.left == null && t.right == null) {
if (tmp+t.val == sum)
return true;
}
tmp += t.val;
if (helper(t.left, tmp, sum)) return true;
if (helper(t.right, tmp, sum)) return true;
return false;
}
}
Leetcode 112. Path Sum
最新推荐文章于 2023-11-14 10:16:47 发布