1. 程式人生 > >leetcode 113. Path Sum II (路徑和) 解題思路和方法

leetcode 113. Path Sum II (路徑和) 解題思路和方法

csdn 節點 consola eno == lin sans 要求 又一

Given a binary tree and a sum, find all root-to-leaf paths where each path‘s sum equals the given sum.

For example:
Given the below binary tree and?sum = 22,
              5
             /             4   8
           /   /           11  13  4
         /  \    /         7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]


思路:此題與上題path sum一脈同源。僅僅是改變了下題目的描寫敘述。詳細思路是用回溯法,將所有的節點所有遍歷。

詳細思路和代碼例如以下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
	/**
	 * 回溯法求解
	 * 總體思想是遍歷。然後加入list逐一試探
	 * 符合要求的加入結果集
	 * 不符合要求的刪除,然後回溯
	 */
    List<List<Integer>> list = new ArrayList<List<Integer>>();
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        if(root == null){
            return list;
        }
        path(root,sum,new ArrayList<Integer>());
        return list;
    }
    
    private void path(TreeNode root,int sum, List<Integer> al){
        if(root == null){
            return;
        }
        if(root.val == sum){
            if(root.left == null && root.right == null){
            	al.add(root.val);
            	//加入結果一定要又一次生成實例
                list.add(new ArrayList<Integer>(al));
                al.remove(al.size()-1);//刪除
                return;
            }
        }
        al.add(root.val);
        path(root.left,sum - root.val,al);
        path(root.right,sum - root.val,al);
        al.remove(al.size()-1);//一定要刪除,確保回溯準確
    }
}




leetcode 113. Path Sum II (路徑和) 解題思路和方法