zoukankan      html  css  js  c++  java
  • 112. Path Sum

    这道题是要判断由根到树叶结点的值的和是否存在等于某个值。主要思路是对树进行前序遍历,依次将结点值相加,当到达树叶结点后直接判断是否等于指定值。

    代码如下:

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 class Solution {
    11     public boolean hasPathSum(TreeNode root, int sum) {
    12         return helper(root, 0, sum);
    13     }
    14     
    15     private boolean helper(TreeNode root, int tmpsum, int sum) {
    16         if(root == null){
    17             return false;
    18         }
    19         
    20         tmpsum += root.val;
    21         if( root.left == null && root.right == null && tmpsum == sum ){
    22             return true;
    23         }
    24         
    25         return helper(root.left, tmpsum, sum) || helper(root.right, tmpsum, sum);    
    26     }
    27 }

    END

  • 相关阅读:
    Spark基础
    flink杂记
    算法
    算法小结
    Java内存模型
    LeetCode---Backtracking && DP
    LeetCode---Sort && Segment Tree && Greedy
    LeetCode---Depth-first && Breadth-first
    LeetCode---Bit Manipulation && Design
    MD5
  • 原文地址:https://www.cnblogs.com/sssysukww/p/8805078.html
Copyright © 2011-2022 走看看