leetcode113---path sum ii



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 andsum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 解题思路:
 1.采用dfs深度优先搜索,左-》根——》右
 2.主要函数返回出口的判定条件 1)root==null(叶子节点)2)root.val==sum 3) 函数执行完左节点和右节点后自然return
 3.不论是满足sum==root.val还是不满足 函数return之前一定要list.remove(list.size()-1); 把最后一个数删除。
 4.每找到一个满足的list 需要alllist.add(new ArrayList<Integer>(list)); list allist设置成全局变量方便一点。
 */
import java.util.ArrayList;
import java.util.List;

public class Solution {
	ArrayList<Integer> list=new ArrayList<Integer>();
	ArrayList<ArrayList<Integer>> alllist=new ArrayList<ArrayList<Integer>>();
	public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
    	
    	if(root==null)
    		return alllist;
    	path(root, sum, list);
        return alllist;
    }
 
    public void path(TreeNode root, int sum,ArrayList<Integer> list)
    {
    	if(root==null)
    		return;
    	list.add(root.val);
    	if(root.left==null&root.right==null&&sum-root.val==0)
    	{
    		alllist.add(new ArrayList<Integer>(list));
    		list.remove(list.size()-1);
    		return;
    	}
    	path(root.left, sum-root.val, list);
    	path(root.right, sum-root.val, list);
    	list.remove(list.size()-1);
    	
    		
    }
}

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 andsum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

return

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

猜你喜欢

转载自blog.csdn.net/ustcyy91/article/details/80080413