zoukankan      html  css  js  c++  java
  • 112. 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.

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean hasPathSum(TreeNode root, int sum) {
            if(root == null) return false;
            
            if(root.left == null&&root.right == null&&sum - root.val == 0){
                return true;
            }
            
            return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);        
        }
    }
    

      

    大道,在太极之上而不为高;在六极之下而不为深;先天地而不为久;长于上古而不为老
  • 相关阅读:
    div 背景透明,字体不透明
    弹性盒子(1)
    小练习(4)
    小练习(3)
    图标文字上拉效果
    小练习(2)
    小练习
    css的使用(1)
    复合的使用
    表单元素的使用 form input
  • 原文地址:https://www.cnblogs.com/GodBug/p/7425612.html
Copyright © 2011-2022 走看看