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

LeetCode47|路径之和

作者头像
码农王同学
发布2020-09-01 10:37:16
2210
发布2020-09-01 10:37:16
举报
文章被收录于专栏:后端Coder

1,问题简述

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

说明: 叶子节点是指没有子节点的节点。

2,示例

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

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

3,题解思路

深度优先搜索

4,题解程序

代码语言:javascript
复制


public class HasPathSumTest {
    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;
        t2.right = t3;
        t2.left=t4;
        t3.left=t5;
        t3.right=t6;
        t4.left=t7;
        t4.right=t8;
        t6.right=t9;
        int sum=22;
        boolean hasPathSum = hasPathSum(t1, sum);
        System.out.println("hasPathSum = " + hasPathSum);


    }

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

5,题解程序图片版

6,总结

深度优先搜索的使用,对于递归的解法,找到规律进行求解就可以了,对于树结构来说,树形结构数据的返回,数据如何加载以及组装都成为了这条道路上必需要走的道路,这可能也是对自己对程序的简单理解吧

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

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

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

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

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