112. Path Sum
原题链接:https://leetcode.com/problems/path-sum/description/
二叉树相关问题,直接深度优先搜索走一波:
/**
* Created by clearbug on 2018/2/26.
*/
public class Solution {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
public static void main(String[] args) {
Solution s = new Solution();
// test1
TreeNode root = new TreeNode(3);
root.left = new TreeNode(9);
root.left.left = new TreeNode(33);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
System.out.println(s.hasPathSum(root, 45));
System.out.println(s.hasPathSum(root, 38));
System.out.println(s.hasPathSum(root, 30));
System.out.println(s.hasPathSum(root, 46));
System.out.println(s.hasPathSum(root, 20));
}
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
return dfs(root, sum, 0);
}
private boolean dfs(TreeNode node, int sum, int currentSum) {
currentSum += node.val;
if (node.left == null && node.right == null) {
if (currentSum == sum) {
return true;
}
} else {
if (node.left != null) {
if (dfs(node.left, sum, currentSum)) {
return true;
}
}
if (node.right != null) {
if (dfs(node.right, sum, currentSum)) {
return true;
}
}
}
return false;
}
}