34_剑指offer_java_二叉树中和为某一值的路径

本文介绍了一道经典的二叉树算法题目,旨在寻找所有从根节点到叶节点的路径,使得路径上节点值的总和等于给定的整数。文章详细解析了题目要求,提供了测试用例,并深入讲解了解题思路,最后给出了Java实现代码。

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

目录

题目描述

测试用例

题目考点

解题思路

参考解题


题目描述

输入一颗二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下直到 叶节点 所经过的节点形成一条路径。二叉树节点的定义如下:

public class BinaryTreeNode {
    int value;
    BinaryTreeNode left;
    BinaryTreeNode right;
}

测试用例

  • 功能测试(二叉树中有一条、多条符合要求的路径;二叉树中没有符合要求的路径)
  • 特殊输入测试(指向二叉树根节点的指针是空指针)

 

题目考点

  • 考察应聘者用例子分析复杂问题的能力。
  • 考察应聘者对二叉树前序遍历的理解。

 

解题思路

对于从节点开始的题目,我们需要想到先序遍历。

  1. 当用前序遍历的方式访问到某一节点时,就把该节点添加到路径数组中。
  2. 如果是叶节点且刚好是我们想要的数,则将它的路径保存起来一份。
  3. 如果当前节点不是叶节点,则继续访问它的子节点。
  4. 当递归函数退出的时候会返回到它的父节点,所以我们需要在删除路径数组的最后一个节点。

 

参考解题

import java.util.ArrayList;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        ArrayList<Integer> singleresult = new ArrayList<>();
        // 异常
        if(root == null){
            return result;
        }
        int CurrentSum = 0;
        // 调用功能函数,改变形参,方便递归
        FindPathCore(root, target, result,singleresult, CurrentSum);
        return result;
    }
    // -----------------功能函数-----------------------------------
    public void FindPathCore(TreeNode node, int target, ArrayList<ArrayList<Integer>> result, ArrayList<Integer> singleresult, int CurrentSum){
        // 更新当前路径、当前和
        CurrentSum += node.val;
        singleresult.add(node.val);
        // 满足条件则将singleresult存入最终result,为一个子序列
        boolean isLeaf = (node.left == null ) && (node.right == null);
        if(isLeaf && CurrentSum == target){
            result.add(new ArrayList<>(singleresult)); // 先添加,再更新??
            //singleresult = new ArrayList<>();  // 更新子序列, 这样写就不对???为啥?
        }
        // 不是叶节点,继续遍历
        if(node.left != null){
            FindPathCore(node.left, target, result, singleresult, CurrentSum);
        }
        if(node.right != null){
            FindPathCore(node.right, target, result, singleresult, CurrentSum);
        }
        // 返回父节点之前,删除路径上当前节点
        singleresult.remove(singleresult.size() - 1);
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值