原创

[百战LeetCode][31.二叉树路径中合为某一值的路径-I]


==========================努力奋斗财源广进==========================

一、算法题目

给定一个二叉树root和一个值 sum ,判断是否有从根节点到叶子节点的节点值之和等于 sum 的路径。

1、我的题解

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @param sum int整型 
     * @return bool布尔型
     */
    public boolean dfs(TreeNode root, int target){
        if(root == null) return false;
        target -= root.val;
        if(root.left == null && root.right == null && target == 0) return true;
        return dfs(root.left, target) || dfs(root.right, target);
    }
    
    public boolean hasPathSum (TreeNode root, int sum) {
        // write code here
        if(root == null) return false;
        return dfs(root, sum);
    }
}

2、优秀题解

//待定

三、解法心得

四、自我监督

评论区记录复习记录

  • 作者:北斗七点半联系作者
  • 发表时间:2022-07-22 21:43
  • 版权声明:禁止转载
  • 非公众号转发
  • 评论