LeetCode47|路径之和

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

1,问题简述

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

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

2,示例

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

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

3,题解思路

深度优先搜索

4,题解程序



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,总结

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