zoukankan      html  css  js  c++  java
  • [Leet Code]Path Sum

    很简单一道题,搞错了N次,记录一下。

    public class Solution {
        private int currSum = 0;
        
        public boolean hasPathSum(TreeNode root, int sum) {
            if (null == root)
                return false;
            
            currSum = 0;
            return hasPathSumCore(root, sum);
        }
        
        public boolean hasPathSumCore(TreeNode root, int sum) {
            // Start typing your Java solution below
            // DO NOT write main() function
            if (null == root)
                return true;
            
            currSum += root.val;
    
            boolean leftHas = false;
            boolean rightHas = false;
            
            if (null == root.left && null == root.right) {
                if (currSum == sum) {
                    currSum -= root.val;
                    return true;
                }
                else {
                    currSum -= root.val;
                    return false;
                }
            }
            else if (null == root.left && null != root.right) {
                rightHas = hasPathSumCore(root.right, sum);
                currSum -= root.val;
                return rightHas;
            }
            else if (null == root.right && null != root.left) {
                leftHas = hasPathSumCore(root.left, sum);
                currSum -= root.val;
                return leftHas;
            }
            else {
                leftHas = hasPathSumCore(root.left, sum);
                rightHas = hasPathSumCore(root.right, sum);
                currSum -= root.val;
                return leftHas || rightHas;
            }
        }
    }
  • 相关阅读:
    无题
    2G日产金士顿
    提防假TF卡,金士顿的识别 (有图)
    无题
    推荐小说
    开学了!
    测速软件
    提供《鬼吹灯》小说系列下载
    换博客了
    Kali_2020.01安装教程
  • 原文地址:https://www.cnblogs.com/lihaozy/p/3208411.html
Copyright © 2011-2022 走看看