二叉树中和为某一值的路径

本文介绍了一种用于寻找二叉树中所有从根节点到叶子节点且节点值之和等于特定数值的路径的算法。该算法通过递归方式遍历二叉树的每个节点,并使用栈来记录路径上的节点值。
/**
 * 二叉树中和为某一值的路径   从树的根节点开始往下一直到叶结点所经过的结点形成的路径
 * @author Q.Yuan
 *
 */
public class BinaryTreePath {
	private Scanner scanner = new Scanner(System.in);
	//先序建立二叉树,测试数据10 5 4 # # 7 # # 12 # #
	public BTreeNode createTree(BTreeNode root){
		String data = scanner.next();
		if(data.equals("#"))
			return null;
		root = new BTreeNode();
		root.data = Integer.valueOf(data);
		root.left = createTree(root.left);
		root.right = createTree(root.right);
		return root;
	}
	/**
	 * 
	 * @param root  树的根节点
	 * @param sum   当前路径之和
	 * @param stack 存放路径上结点的值
	 * @param num   求的路径和
	 */
	public void printPath(BTreeNode root,int sum,Stack<Integer> stack,int num){
		if(root != null){
			sum = sum + root.data;
			stack.push(root.data);
			printPath(root.left, sum, stack, num);
			printPath(root.right, sum, stack, num);
			if(sum == num && root.left == null && root.right == null){
				for(int i:stack){
					System.out.print(i+" ");
				}
				System.out.println();
			}
			stack.pop();
		}
	}
	
	public static void main(String[] args) {
		BinaryTreePath btp = new BinaryTreePath();
		BTreeNode root = null;
		root = btp.createTree(root);
		Stack<Integer> stack = new Stack<Integer>();
		int num = 22;
		int sum = 0;
		btp.printPath(root, sum, stack, num);
	}
}
//树的结构
class BTreeNode{
	Integer data;
	BTreeNode left;
	BTreeNode right;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值