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.

    Note: A leaf is a node with no children.

    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.

    使用递归进行计算,遍历所有的叶结点

    Runtime: 96 ms, faster than 100.00% of C# online submissions for Path Sum.
    Memory Usage: 24 MB, less than 68.75% of C# online submissions for Path Sum.
    public bool HasPathSum(TreeNode root, int sum)
            {
                if (root == null)
                {
                    return false;
                }
                return Sum(root, sum, 0);
            }
    
            public bool Sum(TreeNode node, int target, int tempSum)
            {
                tempSum = tempSum + node.val;
                var left = node.left;
                var right = node.right;
                if (left == null && right == null)
                {
                    return tempSum == target;
                }
                else if (left != null && right == null)
                {
                    return Sum(left, target, tempSum);
                }
                else if (left == null && right != null)
                {
                    return Sum(right, target, tempSum);
                }
                else if (left != null && right != null)
                {
                    bool flag1 = Sum(left, target, tempSum);
                    if (flag1)
                    {
                        return true;
                    }
                    bool flag2 = Sum(right, target, tempSum);
                    if (!flag2)
                    {
                        return false;
                    }
                }
    
                return true;
            }
  • 相关阅读:
    ES6 基础
    JavaScript 基础
    Java 虚拟机
    MinIO 搭建使用
    .NET 半天搭建Jenkins持续集成与自动化部署系统
    驱动领域DDD的微服务设计和开发实战
    走向架构师必备的技能
    分布式系统与消息的投递¶
    求数组的子数组之和的最大值
    KVO初探
  • 原文地址:https://www.cnblogs.com/chucklu/p/10695382.html
Copyright © 2011-2022 走看看