4.9

Topic 4.9 You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum to a given value. Note that a path can start or end anywhere in the tree.

//路径被存在一个数组里
public class c4_9 {
	
	public static void findSum(TreeNode node, int sum, int[] path, int level) {
		if (node == null) {
			return;
		}

		/* Insert current node into path */
		path[level] = node.data; //树还是从上往下加,把每条路径放在path里(每找一个sum,都是从第一层往最后一层,找个遍,是很麻烦

		int t = 0;
		for (int i = level; i >= 0; i--){//这里的时候,把path从后往前加,等于sum就打印
			t += path[i];
			if (t == sum) {
				print(path, i, level);
			}
		}

		findSum(node.left, sum, path, level + 1);
		findSum(node.right, sum, path, level + 1);
	}
	
	//返回一棵树的深度,从1开始数
	public static int depth(TreeNode node) {
		if (node == null) {
			return 0;
		} else {
			return 1 + Math.max(depth(node.left), depth(node.right));
		}
	}

	public static void findSum(TreeNode node, int sum) {
		int depth = depth(node);
		int[] path = new int[depth];
		findSum(node, sum, path, 0);
	}

	private static void print(int[] path, int start, int end) {
		for (int i = start; i <= end; i++) {
			System.out.print(path[i] + " ");
		}
		System.out.println();
	}

	public static void main(String [] args){
		int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};  
        TreeNode root = TreeNode.createMinimalBST(array);
		findSum(root, 8);
	}
}
//结果
5 2 1 
8 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值