LeetCode101|路径总和

时间:2022-07-28
本文章向大家介绍LeetCode101|路径总和,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

0x01, 问题简述

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。说明: 叶子节点是指没有子节点的节点。

0x02,示例

示例: 
给定如下二叉树,以及目标和 sum = 22,

              5
             / 
            4   8
           /   / 
          11  13  4
         /        
        7    2      1
返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。

0x03,题解思路

递归方法的使用

0x04,题解程序


public class HashPathSumTest {
    public static void main(String[] args) {
        TreeNode t1 = new TreeNode(5);
        TreeNode t2 = new TreeNode(4);
        TreeNode t3 = new TreeNode(8);
        TreeNode t4 = new TreeNode(11);
        TreeNode t5 = new TreeNode(13);
        TreeNode t6 = new TreeNode(4);
        TreeNode t7 = new TreeNode(7);
        TreeNode t8 = new TreeNode(2);
        TreeNode t9 = new TreeNode(1);
        t1.left = t2;
        t1.right = t3;
        t2.left = t4;
        t3.left = t5;
        t3.right = t6;
        t4.left = t7;
        t4.right = t8;
        t6.right = t9;
        int sum = 22;
        boolean hashPathSum = hashPathSum(t1, sum);
        System.out.println("hashPathSum = " + hashPathSum);


    }

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

0x05,题解程序图片版

0x06,总结一下

对于这道题,慢一点,才能更快,98道leetcode想到的就是利用递归的思路进行,递归的本质还是利用系统栈的特点也保存了数据,找到递归的结束条件和递归子问题就可以了。