Cracking the coding interview--Q4.8

本文介绍了一种算法,用于查找二叉树中所有节点值之和等于给定值的路径。这些路径可能从任意节点开始,不仅限于根节点。通过递归遍历并利用指向父节点的指针实现。

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

题目

原文:

You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum up to that value. Note that it can be any path in the tree - it does not have to start at the root.

译文:

给一个每个结点都包含一个值的二叉树,设计一个算法打印所有满足这个条件的路径:路径上结点的值加起来等于给定的一个值。注意:这些路径不一定从根节点开始。

解答

结点中包含指向父亲结点的指针,那么,只需要去遍历这棵二叉树, 然后从每个结点开始,不断地去累加上它父亲结点的值直到父亲结点为空(这个具有唯一性, 因为每个结点都只有一个父亲结点。也正因为这个唯一性, 可以不另外开额外的空间来保存路径),如果等于给定的值sum,则打印输出。

代码如下:

import java.util.Stack;

class Q4_8{
	public static void findSum(TreeNode head,int sum){
		if(head==null) return;
		TreeNode tnode=head;
		int tmp=0;
		for(int i=1;tnode!=null;i++){
			tmp+=tnode.value;
			if(tmp==sum)
				print(head,i);
			tnode=tnode.parent;
		}
		findSum(head.lchild,sum);
		findSum(head.rchild,sum);
	}
	private static void print(TreeNode tnode,int level){
		Stack<Integer> s=new Stack<Integer>();
		for(int i=0;i<level;i++){
			s.push(tnode.value);
			tnode=tnode.parent;
		}
		while(s.size()>0){
			System.out.print(s.pop()+" ");
		}
	}
	public static void main(String[] args){
		int[] arr={5,1,3,8,6,10};
		TreeNode root=TreeNode.createBinaryTree(arr);
		findSum(root,23);
	}
}

---EOF---


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值