1. 程式人生 > >[Leetcode] 112. 路徑總和 java

[Leetcode] 112. 路徑總和 java

 給定一個二叉樹和一個目標和,判斷該樹中是否存在根節點到葉子節點的路徑,這條路徑上所有節點值相加等於目標和。

說明: 葉子節點是指沒有子節點的節點。

示例: 
給定如下二叉樹,以及目標和 sum = 22

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

返回 true, 因為存在目標和為 22 的根節點到葉子節點的路徑 5->4->11->2

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root==null) return false;
        if(root.left==null&&root.right==null){
            if(root.val==sum) return true;
            else return false;
        }
        if(root.left==null) return hasPathSum(root.right,sum-root.val);
        if(root.right==null) return hasPathSum(root.left,sum-root.val);
        return hasPathSum(root.right,sum-root.val)||hasPathSum(root.left,sum-root.val);
    }
}