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

/**
 * 二叉树中和为某一值的路径
 * 递归迭代的过程
 * */

public class A04 {
	
	public Stack<Node> stack = new Stack<Node>();
	
	static class Node{
		public int content;
		public Node Left;
		public Node Right;
		public int getContent() {
			return content;
		}
		public void setContent(int content) {
			this.content = content;
		}
		public Node getLeft() {
			return Left;
		}
		public void setLeft(Node left) {
			Left = left;
		}
		public Node getRight() {
			return Right;
		}
		public void setRight(Node right) {
			Right = right;
		}
		public Node(int value){
			content = value;
		}
	}

	static class Tree{
		public final Node rootNode = new Node(10);	
		public Node getRootNode () {
			
			
			Node node5 = new Node(5);
			rootNode.setLeft(node5);
			Node node6 = new Node(6);
			node5.setLeft(node6);
			Node node7 = new Node(7);
			Node node11 = new Node(11);
			Node node1 = new Node(1);
			Node node2 = new Node(2);
			node11.setLeft(node1);
			node11.setRight(node1);
			node1.setLeft(node2);
			node7.setLeft(node2);
			rootNode.setRight(node11);
			node5.setRight(node7);
			return rootNode;
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Tree tree = new Tree();
		int sum = 24;
		A04 a4 = new A04();
		a4.findSumPath(tree.getRootNode(),sum);

	}
	/**
	 * 
	 */
	private  void findSumPath(Node node ,int sum) {
		
		if(node == null){
			return ;
		}
		
		if(node.getContent() > sum){
			return ;
		}
		
		if(node.getContent() < sum){
			stack.push(node);//压栈
			if(node.getLeft() != null){	
				findSumPath(node.getLeft(), sum-node.getContent());	
			}
			
			if(node.getRight() != null){
				findSumPath(node.getRight(), sum-node.getContent());
				
			}
		}
		
		if(node.getContent() == sum){
			stack.push(node);//如果节点是合适的,压栈后,打印出栈
			print(stack);
			stack.pop();
			return;
		}
		
		stack.pop();//如果节点不合适,直接的出栈
		
	}
	/**
	 * @param stack2
	 */
	private void print(Stack<Node> stack2) {
		for(Node node:stack2){
			System.out.print(node.content + "  ");
		}
		
	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值