1. 程式人生 > >LeetCode112. 路徑總和

LeetCode112. 路徑總和

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

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

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

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

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

思路:採用回溯演算法,深度優先遍歷,記錄下每一條路徑的和,如果有符合條件的路徑和則返回true,否則返回false。

/**
 * 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(null==root){
            return false;
        }
        List<Integer> list=new LinkedList<Integer>();//臨時儲存深度優先遍歷結果
        List<Integer> res=new LinkedList<Integer>(); //儲存所有根結點到葉子結點的路徑和
         dfs(root,list,0,res);
         for(Integer i:res){
             if(i==sum){
                 return true;
             }
         }
         return false;
    }
     public  void dfs(TreeNode root, List<Integer> list,int tmp,List<Integer> res){
        if(null==root){
           return ;
        }

        list.add(root.val);
        tmp+=root.val;

        if(null==root.left&&null==root.right){
            res.add(tmp);
        }
        dfs(root.left,list,tmp,res);
        dfs(root.right,list,tmp,res);
        tmp-=list.get(list.size()-1);
        list.remove(list.size()-1);

    }
}

解法二:採用遞迴的思想深度優先遍歷二叉樹,在遍歷的過程中(即遍歷到葉子結點時)判斷這一條路徑是否符合條件。推薦使用第二種解法。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
  public boolean hasPathSum2(TreeNode root,int sum){

        return hasSum(root,0,sum);
    }

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