zoukankan      html  css  js  c++  java
  • 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);
        }
    }
    
    
    
     
  • 相关阅读:
    因为公司项目需要,我要学习PB了,哎
    送给自己人生的第一份生日礼物——Java小游戏!
    第二讲 Java 开发环境搭建
    IT学生关于“怎么学习”的思考,这也是其他人思考的问题吗?
    第四讲 类与对象
    第一讲 Java 介绍
    第三讲 Java 基本数据类型+运算符
    初步理解Lambda表达式的简单实现
    一道关于pack()和sizeof笔试题
    排序源码(待续)
  • 原文地址:https://www.cnblogs.com/softwarewebdesign/p/5511489.html
Copyright © 2011-2022 走看看