LeetCode112——路径总和

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/path-sum/description/

题目描述:

知识点:递归、树的深度优先遍历

思路一:递归

递归终止条件

(1)如果root为null,返回false。

(2)如果root的值为sum且root的左右孩子均为null,返回true。

递归过程

sum减去root的值并递归判断其左子树或右子树是否有等于sum的路径。

时间复杂度和空间复杂度均是O(h),其中h为树的高度。

JAVA代码:

public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root == null) {
            return false;
        }
        if(root.val == sum && root.left == null && root.right == null) {
            return true;
        }
        sum -= root.val;
        return hasPathSum(root.left, sum) || hasPathSum(root.right, sum);
    }
}

LeetCode解题报告:

思路二:深度优先遍历

本质上和思路一是一致的。

时间复杂度和空间复杂度均是O(h),其中h为树的高度。

JAVA代码:

public class Solution {
    boolean flag = false;

    public boolean hasPathSum(TreeNode root, int sum) {
        if(null == root){
            return flag;
        }
        dfs(root, sum);
        return flag;
    }

    private void dfs(TreeNode root, int sum) {
        if(null == root.left && null == root.right){
            sum -= root.val;
            if(sum == 0){
                flag = true;
            }
            return;
        }
        if(null != root.left){
            dfs(root.left, sum - root.val);
        }
        if(null != root.right){
            dfs(root.right, sum - root.val);
        }
    }
}

LeetCode解题报告:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值