1. 程式人生 > >[LeetCode]Path Sum系列

[LeetCode]Path Sum系列

post 條件 paths path sum 發現 負數 gpo span 二叉樹

1.二叉樹路徑求指定和,需要註意的是由於有負數,所以即使發現大於目標值也不能返回false,而且返回true的條件有兩個,到葉節點且等於sum,缺一不可

public boolean hasPathSum(TreeNode root, int sum) {
        if (root==null) return false;
        if (root.val==sum&&root.left==null&&root.right==null) return true;
        else return hasPathSum(root.left,sum-root.val)||hasPathSum(root.right,sum- root.val);
    }

2.

3.

4.

[LeetCode]Path Sum系列