Tree_Graph 打印所有和为定值的路径 @CareerCup

原文:

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.

译文:

给定一棵二叉树,每个结点包含一个值。打印出所有满足以下条件的路径: 路径上结点的值加起来等于给定的一个值。注意:这些路径不必从根结点开始。


思路:

非常好的一题!时间复杂度:O(nlogn),空间复杂度:O(logn)

结合了回溯和另外一个重要思想!


就是下面的代码:在path数组里保存着当前的路径,以及当前的层level,然后我们可以由当前层往上遍历,看能不能凑到sum

		// 统计从level(当前层)往上走,能否凑到sum
		// 重要思想!
		int t = 0;
		for(int i=level; i>=0; i--) {
			t += path[i];
			if(t == sum) {
				print(path, i, level);		// i: start, level: end
			}
		}

下面是总的代码:

package Tree_Graph;

import CtCILibrary.TreeNode;

public class S4_9 {

	public static void findSum(TreeNode root, int sum) {
		int depth = depth(root);
		int[] path = new int[depth];			// 建一个path数组,存放每一层的值
		findSum(root, sum, path, 0);
	}
	
	// 递归打印所有可能
	// path数组保存当前走过的路线,level表示当前到达的层
	public static void findSum(TreeNode root, int sum, int[] path, int level) {
		if(root == null){
			return;
		}
		
		path[level] = root.data;		// 先为当前层赋值
		
		// 统计从level(当前层)往上走,能否凑到sum
		// 重要思想!
		int t = 0;
		for(int i=level; i>=0; i--) {
			t += path[i];
			if(t == sum) {
				print(path, i, level);		// i: start, level: end
			}
		}
		
		findSum(root.left, sum, path, level+1);
		findSum(root.right, sum, path, level+1);
		
		path[level] = Integer.MIN_VALUE;		// 撤销当前层赋值
	}
	
	// 求高度
	public static int depth(TreeNode root) {
		if(root == null) {
			return 0;
		}
		return 1 + Math.max(depth(root.left), depth(root.right));
	}
	
	public 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){
		TreeNode root = new TreeNode(5);
		root.left = new TreeNode(3);
		root.right = new TreeNode(1);
		root.left.left = new TreeNode(4);
		root.left.right = new TreeNode(8);
		root.right.left = new TreeNode(2);
		root.right.right = new TreeNode(6);
		findSum(root, 8);
	}
}






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值