前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode101|路径总和

LeetCode101|路径总和

作者头像
码农王同学
发布2020-10-27 18:12:32
3000
发布2020-10-27 18:12:32
举报
文章被收录于专栏:后端Coder

0x01, 问题简述

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

0x02,示例

代码语言:javascript
复制
示例: 
给定如下二叉树,以及目标和 sum = 22,

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

0x03,题解思路

递归方法的使用

0x04,题解程序

代码语言:javascript
复制

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想到的就是利用递归的思路进行,递归的本质还是利用系统栈的特点也保存了数据,找到递归的结束条件和递归子问题就可以了。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-10-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 码农王同学 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档