Path Sum Path Sum II

本文深入探讨了二叉树路径和问题的两种不同算法实现:一是判断是否存在根到叶节点路径使得路径上所有数值之和等于给定的值;二是找出所有满足条件的路径并打印出来。通过具体实例和代码解释了递归方法的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目github地址:bitcarmanlee easy-algorithm-interview-and-practice
欢迎大家star,留言,一起学习进步

1.Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

上面的题只需要判断是否有条路径的和为sum,而不需要求出所有的路径。

    public static boolean findPathSum(TreeNode<Integer> root, int sum) {
        if (root == null) {
            return false;
        }

        if (root.left == null && root.right == null) {
            return root.data == sum;
        }

        return (root.left != null && findPathSum(root.left, sum - root.data)) ||
                (root.right != null && findPathSum(root.right, sum - root.data));
    }

上面的代码,会沿着root先递归到最下面一个左子节点。假设此条路径就刚好满足和为sum,此时

        if (root.left == null && root.right == null) {
            return root.data == sum;
        }

会返回true。那么root.left != null && findPathSum(root.left, sum - root.data)会沿着堆栈信息一直回去返回true,后面的root.right != null && findPathSum(root.right, sum - root.data)这行不再被执行!
如果中间任意一条路径的和刚好满足sum,具体的逻辑跟上面是一致的。

2.Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

For example:
Given the below binary tree and sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

这道题要求将路径和为sum的所有路径都数出来,那么至少需要将树的所有路径都遍历,同时判断每条路径的和,看是否等于sum。如果相等则输出。

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wanglei on 19/4/16.
 */
public class TreePathSum {

    public static List<String> list = new ArrayList<>();
    public static int target = 22;

    public static TreeNode<Integer> init() {
        TreeNode<Integer> root = new TreeNode<>(5);
        TreeNode<Integer> node4 = new TreeNode<>(4);
        TreeNode<Integer> node8 = new TreeNode<>(8);
        TreeNode<Integer> node11 = new TreeNode<>(11);
        TreeNode<Integer> node13 = new TreeNode<>(13);
        TreeNode<Integer> node42 = new TreeNode<>(4);
        TreeNode<Integer> node7 = new TreeNode<>(7);
        TreeNode<Integer> node2 = new TreeNode<>(2);
        TreeNode<Integer> node5 = new TreeNode<>(5);
        TreeNode<Integer> node1 = new TreeNode<>(1);
        root.left = node4;
        root.right = node8;
        node4.left = node11;
        node8.left = node13;
        node8.right = node42;
        node11.left = node7;
        node11.right = node2;
        node42.left = node5;
        node42.right = node1;

        return root;
    }
    
    public static void findPathSum2(TreeNode<Integer> root, int sum, String path, List<String> res) {
        if (root == null) {
            return;
        }

        if (root.left == null && root.right == null) {
            if (sum == target) {
                res.add(path);
            }
            return;
        }

        if (root.left != null) {
            findPathSum2(root.left, sum + root.left.data, path + "->" + root.left.data, res);
        }
        if (root.right != null) {
            findPathSum2(root.right, sum+root.right.data, path +"->" + root.right.data, res);
        }

    }

    public static void printList(List<String> input) {
        for(String ele: input) {
            System.out.println(ele);
        }
    }

    public static void main(String[] args) {
        TreeNode<Integer> root = init();
        findPathSum2(root, root.data, root.data.toString(), list);
        printList(list);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值