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 =


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.

代码 1

复制代码
import java.util.ArrayList;

class TreeNode {
          int val;
          TreeNode left;
          TreeNode right;
          TreeNode(int x) { val = x; }
      }
public class Solution {
    ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> arr=new ArrayList<Integer>();
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root==null)return false;
        isPath(root,0,sum);
        if(result.isEmpty())return false;
        else return true;
        
    }
    private void isPath(TreeNode root, int sum, int target) {
        if(root==null)return;
        else{
            sum+=root.val;
            arr.add(root.val);
            if(root.left==null&&root.right==null&&sum==target){
                result.add(new ArrayList<Integer>(arr));
            }
            isPath(root.left, sum, target);
            isPath(root.right, sum, target);
            arr.remove(arr.size()-1);
            sum-=root.val;
        }
        
    }
}

代码二:
复制代码
import java.util.ArrayList;

class TreeNode {
          int val;
          TreeNode left;
          TreeNode right;
          TreeNode(int x) { val = x; }
      }
public class Solution {

     public boolean hasPathSum(TreeNode root, int sum) {
            return hasPathSumHelper(root, sum);
       }

    private boolean hasPathSumHelper(TreeNode root, int sum) {
        // TODO Auto-generated method stub
        if(root==null)return false;
        if(root.left==null&&root.right==null&&sum==root.val)return true;
        return hasPathSumHelper(root.left, sum-root.val)||hasPathSumHelper(root.right, sum-root.val);
    }
}
复制代码

 

 
复制代码

 

posted @ 2016-05-20 11:33  Adding  阅读(167)  评论(0)    收藏  举报
编辑推荐:
· 糊涂啊!这个需求居然没想到用时间轮来解决
· 浅谈为什么我讨厌分布式事务
· 在 .NET 中使用内存映射文件构建高性能的进程间通信队列
· 一个 java 空指针异常的解决过程
· 揭开 SQL Server 和 PostgreSQL 填充因子的神秘面纱
阅读排行:
· 从硬盘爆满到 GitHub 封号,一位前端开发者的开源历险记
· 微软又一自动化开源王炸,Selenium 慌了!
· 微服务的10大问题
· C#解析JSON数据全攻略
· 上周热点回顾(7.14-7.20)
点击右上角即可分享
微信分享提示