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

    Tips:在一个给定的树上找出是否包含和为sum的路径(路径指从root到根节点)

    我采用的递归方法,root有左子树,就用root.left调用作为参数,再次调用函数。

    root有右子树,就用root.right调用作为参数,再次调用函数。

    public boolean hasPathSum(TreeNode root, int sum) {
            if (root == null)
                return false;
            boolean has = false;
            int ans = 0;
            has = hasPathSumCore(root, sum, ans);
            return has;
        }
    
        private boolean hasPathSumCore(TreeNode root, int sum, int ans) {
            // TODO Auto-generated method stub
            boolean has = false;
            if (root == null) {
                System.out.println("null");
                return false;
            }
            ans += root.val;
            System.out.println(ans);
            if (ans == sum && root.left == null && root.right == null) {
                has = true;
            }
            if (root.left != null) {
                boolean has1 = hasPathSumCore(root.left, sum, ans);
                has = has || has1;
            }
            if (root.right != null) {
                boolean has2 = hasPathSumCore(root.right, sum, ans);
                has = has || has2;
            }
            ans -= root.val;
    
            return has;
    
        }

    之后在leetcode上看到更简单的做法(-_-||)

    public boolean hasPathSum2(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);
            }
  • 相关阅读:
    nikto web server 扫描工具
    crowdsec开源安全引擎
    windows strace 类似的工具
    禁用spring boot 暴露的几个产品可用的endppint 服务
    nginx proxy minio 默认页配置(三)
    nginx proxy minio 默认页配置(二)
    nginx proxy minio 默认页配置
    flamescope + chrome cpu profile 分析web 性能
    golang noCopy 的功能
    golang 死锁&&静态检查的一些工具
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/8424534.html
Copyright © 2011-2022 走看看