2015-10-17 83 views
1

問題 - >給定一棵二叉樹和一個和,確定樹是否具有根到葉的路徑,以便沿路徑加起來的所有值等於給定的總和。樹 - 路徑總和

我的解決方案 - >

public class Solution { 
    public boolean hasPathSum(TreeNode root, int sum) { 
     if (root == null || sum == 0){ 
      return false; 
     } 
     List<Integer> resultSet = new ArrayList<Integer>(); 
     Integer result = root.val; 
     inorder(root, result, resultSet); 
     return resultSet.contains(sum); 
    } 
    public void inorder(TreeNode root, Integer result, List<Integer> resultSet){ 
     if (root.left == null && root.right == null){ 
      resultSet.add(result); 
     } 
     if (root.left != null) { 
      result += Integer.valueOf(root.left.val); 
      inorder(root.left, result, resultSet); 
     } 
     if (root.right != null) { 
      result += Integer.valueOf(root.right.val); 
      inorder(root.right, result, resultSet); 
     } 

    } 
} 

輸出 - >

輸入: [1,-2,-3,1,3,-2,空,-1] 輸出:true 預計:假

我真的不知道我在哪裏出錯了。我嘗試使用int和Integer類型選項來獲得結果,但它不起作用。請幫忙。

回答

1

我看到的問題是result可變的,因爲一旦你添加值left節點到result並與left樹完成那麼你也會的right child值添加到結果,這是錯誤的,因爲現在是具有leftright子值的總和。

所以基本上你在 在inorder遍歷節點root之前來的result將所有的節點的值。

你可以試試這個:

public void inorder(TreeNode root, Integer result, List<Integer> resultSet){ 
    if (root.left == null && root.right == null){ 
     resultSet.add(result); 
    } 
    if (root.left != null) { 
     inorder(root.left, result+Integer.valueOf(root.left.val), resultSet); 
    } 
    if (root.right != null) { 
     inorder(root.right, result+Integer.valueOf(root.right.val), resultSet); 
    } 
} 

編輯:1

另一種簡單的方法來解決這個問題:你並不需要創建一個包含所有的根葉之和陣列路徑。你可以簡單地保持遞減所需的總和。

代碼:

public boolean hasPathSum(TreeNode root, int sum) { 
    if (root == null) { 
     return false; 
    } else { 
     return hasPathSumHelper(root, sum); 
    } 

} 

boolean hasPathSumHelper(TreeNode root, int sum) { 
    if (root.left == null && root.right == null) {//if leaf node 
     if (Integer.valueOf(root.val) == sum) { //if node value is equal to sum 
      return true; 
     } else { 
      return false; 
     } 
    } 
    if ((root.left != null) && (root.right != null)) { 
     return (hasPathSumHelper(root.left, sum - Integer.valueOf(root.val)) || hasPathSumHelper(root.right, sum - Integer.valueOf(root.val))); 
    } 
    if (root.left != null) { 
     return hasPathSumHelper(root.left, sum - Integer.valueOf(root.val)); 
    } else { 
     return hasPathSumHelper(root.right, sum - Integer.valueOf(root.val)); 
    } 
} 
+0

嘿,這沒有奏效。不,我沒有在一個級別添加左側和子節點值。我將通過遞歸調用深入一層,然後只添加結果。 輸入: [7,0,NULL,-1,-6,空,1,NULL,NULL,-7] 輸出: 假 預期: 真 所以,基本上我加入節點值只在不同的級別,然後檢查我是否遇到了葉節點。我使用了類似的代碼來查找樹中的不同路徑。所以認爲這種方法也適用於這個問題,但是我會出錯的地方。 – Afan

+0

我發佈了另一種解決此問題的方法。檢查出。你也可以嘗試打印出你的結果數組,看看它有什麼不同的路徑。這將有助於用您當前的方法調試問題 – pgiitu

+1

是的,謝謝!後來我嘗試了一種類似的方法,它工作。 – Afan