树-Path Sum II(指定和,求根到叶子的路径)

本文介绍了一种使用深度优先搜索算法的方法,用于查找二叉树中所有从根节点到叶子节点的路径,使得这些路径的元素之和等于给定的数值。通过递归地遍历树结构,算法能够有效地识别满足条件的路径。

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

题目:

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

return

[
   [5,4,11,2],
   [5,8,4,5]
]

思考:

想了大半天,参考了往上的办法,深度优先搜索,先从根节点的左儿子的左儿子...一直到叶子位置,那么这就是第一条路径了,路径和为参数就加入保存路径的list,否则删掉这个叶子,查看这个节点的兄弟试试看,也就是这个叶子的父节点的有儿子(有的话),采用递归,以此类推。

代码(java):

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> totalPath = new ArrayList<List<Integer>>();
		int total = 0;
		List<Integer> currentPath = new ArrayList<Integer>();
			
		find(root, sum, currentPath, total, totalPath);


		return totalPath;
    }
    
    
    
    
    
    public void find(TreeNode root, int sum, List<Integer> currentPath, int total, List<List<Integer>> totalPath){
		
		if(root == null){
			return;
		}
		currentPath.add(root.val);
		total = total + root.val;
		
		
		if(root.left == null && root.right == null && total == sum){		
			totalPath.add(new ArrayList(currentPath));	
			return;
		}
		
		//首先会一直遍历left,然后才是慢慢的往上走,取查看他的兄弟,所以需要删除最后一个!
		if(root.left != null){
			//currentPath.add(root.val);
			//total = total + root.val;
			find(root.left, sum, currentPath, total, totalPath);
			
			currentPath.remove(currentPath.size() - 1);
		}
		
		if(root.right != null){
			//currentPath.add(root.val);
			//total = total + root.val;
			find(root.right, sum, currentPath, total, totalPath);
			
			currentPath.remove(currentPath.size() - 1);
		}
		
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值