zoukankan      html  css  js  c++  java
  • Path Sum

    https://leetcode.com/problems/path-sum/

    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 and sum = 22,

                  5
                 / 
                4   8
               /   / 
              11  13  4
             /        
            7    2      1
    

    return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

     1 public class Solution {
     2 //    private static boolean flag=false;
     3 //    public static boolean hasPathSum(TreeNode root, int sum) {
     4 //    if(root==null){return flag;}
     5 ////    if(root.left==null&&root.right==null&&root.val==1&&sum==0)return false;
     6 //        F(0,root,sum);
     7 //    return flag;
     8 //    }
     9 //    public static void F(int cout,TreeNode node,int sum){
    10 //    if(flag==true){return;}
    11 //    cout+=node.val;
    12 //    if(node.left==null&&node.right==null&&cout==sum){flag=true;return;}
    13 //    if(node.left!=null){F(cout,node.left,sum);}
    14 //    if(node.right!=null){F(cout,node.right,sum);}
    15 //    }
    16     public static boolean hasPathSum(TreeNode root, int sum) {
    17     if (root == null)
    18         return false;
    19 
    20     if (root.left == null && root.right == null)
    21         return sum == root.val;
    22 
    23     return hasPathSum(root.left, sum - root.val)
    24         || hasPathSum(root.right, sum - root.val);
    25     }
    26     public static class TreeNode {
    27     int val;
    28     TreeNode left;
    29     TreeNode right;
    30 
    31     TreeNode(int x) {
    32         val = x;
    33     }
    34     }
    35     public static void main(String[]args){
    36     TreeNode[] node=new TreeNode[5];
    37     for(int i=0;i<node.length;i++){
    38         node[i]=new TreeNode(i);
    39     }
    40     TreeNode node1=new TreeNode(1);
    41     TreeNode node2=new TreeNode(2);
    42 //    node1.left=node2;
    43     node[0].left=node[1];
    44     node[0].right=node[2];
    45     node[1].left=node[3];
    46     node[2].right=node[4];
    47     System.out.println(hasPathSum(node1,2));
    48     }
    49 }
  • 相关阅读:
    Python打包方法——Pyinstaller
    在线检测显示器屏幕尺寸
    python_分布式进程中遇到的问题
    软件测试面试题(一)
    Django在根据models生成数据库表时报 __init__() missing 1 required positional argument: 'on_delete'
    mac系统 安装 IPython
    京东自动抢茅台脚本 Python
    CMake使用总结(一)
    小白安装eclipse插件—>testNG
    离线安装eclipse-testNG插件
  • 原文地址:https://www.cnblogs.com/qq1029579233/p/4478091.html
Copyright © 2011-2022 走看看