码迷,mamicode.com
首页 > 其他好文 > 详细

113. Path Sum II

时间:2016-09-24 07:07:27      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

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]
]

理解下leaf node:先序遍历,先加root,然后遍历左右子树,如果都为null(遍历完),回溯。
4
/ \
null null
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res=new ArrayList<>();
        List<Integer> check=new ArrayList<Integer>();
        dps(root,res,check,sum);
        return res;
    }
    public void dps(TreeNode root, List<List<Integer>> res,List<Integer> check,int sum)
    {
        if(root==null)
        {
            return;
        }
         check.add(root.val);
        if(root.left==null&&root.right==null&&sum==root.val)
        {
                res.add(new ArrayList<>(check));
        }
        else
        {
        dps(root.left,res,check,sum-root.val);
        dps(root.right,res,check,sum-root.val);
        }
        check.remove(check.size()-1);
    }
        
    
}

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res=new ArrayList<>();
        List<Integer> check=new ArrayList<Integer>();
        dps(root,res,check,sum);
        return res;
    }
    public void dps(TreeNode root, List<List<Integer>> res,List<Integer> check,int sum)
    {
        if(root==null)
        {
            return;
        }
        if(root.left==null&&root.right==null)
        {
            if(sum==root.val)
            {   
                List<Integer> tmp=new ArrayList<>(check);
                tmp.add(root.val);
                res.add(tmp);
            }
            return;
        }
        check.add(root.val);
        dps(root.left,res,check,sum-root.val);
        dps(root.right,res,check,sum-root.val);
        check.remove(check.size()-1);
    }
        
    
}

 

113. Path Sum II

标签:

原文地址:http://www.cnblogs.com/Machelsky/p/5902332.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!