1. 程式人生 > >判斷二叉樹的路徑和是否和給定數值相等

判斷二叉樹的路徑和是否和給定數值相等

package niuke.day1;

import java.util.Stack;
/*Given a binary tree and a sum, determine if the tree has a root-to-leaf path such
that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree andsum = 22,

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

return true, as there exist a root-to-leaf path5->4->11->2which sum is 22. */

//其實本題並沒有重複的子問題,無需考慮動態規劃,單純的遞迴完全可以解決問題

public class Path_Sum {
     public static void main(String[] args) {
         TreeNode t1 = new TreeNode(1);
         TreeNode t2 = new TreeNode(2);
         t1.right = t2;
         System.out.println(hasPathSum(t1, 3));
        
        
    }
       static Stack<TreeNode> s = new Stack<>();  //本題利用棧替代了遞迴的過程,事實證明我還是不擅長遞迴
       static boolean flag = false;    //定義標誌位
     public static boolean hasPathSum(TreeNode root, int sum) {
         if(root != null)
             s.push(root);
         while(!s.isEmpty() && flag != true) { //當棧不為空或者還沒有找到符合條件的路徑則一直迴圈
             TreeNode temp = s.pop();
             if(temp.val == sum && temp.left == null && temp.right == null) {
                 flag = true;    //正好是葉子節點,又恰好滿足條件則修改標誌位
             }
             if(temp.left != null ) {
                 temp.left.val += temp.val;  
                 hasPathSum(temp.left, sum);//當左子樹不為空的時候則繼續呼叫自己
             }
             if(temp.right != null ) {
                 temp.right.val += temp.val;
                 hasPathSum(temp.right, sum);
             }
            
         }
        return flag;
    
        //以下是來自網友的另一種解法
         /*public boolean hasPathSum(TreeNode root, int sum) {
                if(root==null){
                    return false;         //我常犯的錯誤就是把遞迴裡的返回值理解為是整體的返回,其實這只是遞迴的一步返回
                }
                if(root.left==null &&root.right==null){//當是葉子節點的時候
                    if(sum-root.val==0){
                        return true;  //如果滿足結果則返回true
                    }else{
                        return false;  //否則就返回false
                    }
                }
                boolean left=hasPathSum(root.left,sum-root.val); //理解的重點,不斷的遞迴
                boolean right=hasPathSum(root.right,sum-root.val);
                return left||right;//當左子樹滿足或者右子樹滿足都可以,當底層的樹滿.足會不斷的返回,直到返回最上層,還是要深入理解遞迴的思路
            }*/
         
     }
}