找出二元树中和为某一值的所有路径

题目:输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。打印出和与输入整数相等的所有路径。

例如输入整数22和如下二元树

                                            10
                                           /   \
                                          5     12
                                        /   \  
                                      4     7 

则打印出两条路径:10, 12和10, 5, 7。

二元树结点的数据结构定义为:

struct BinaryTreeNode // a node in the binary tree
{
      int              m_nValue; // value of node
      BinaryTreeNode  *m_pLeft;  // left child of node
      BinaryTreeNode  *m_pRight; // right child of node
};

分析:这是百度的一道笔试题,考查对树这种基本数据结构以及递归函数的理解。

当访问到某一结点时,把该结点添加到路径上,并累加当前结点的值。如果当前结点为叶结点并且当前路径的和刚好等于输入的整数,则当前的路径符合要求,我们把它打印出来。如果当前结点不是叶结点,则继续访问它的子结点。当前结点访问结束后,递归函数将自动回到父结点。因此我们在函数退出之前要在路径上删除当前结点并减去当前结点的值,以确保返回父结点时路径刚好是根结点到父结点的路径。我们不难看出保存路径的数据结构实际上是一个栈结构,因为路径要与递归调用状态一致,而递归调用本质就是一个压栈和出栈的过程。

参考网址:http://zhedahht.blog.163.com/blog/static/254111742007228357325/

 

import java.util.LinkedList;


public class Test_04 {
	public static void main(String[] args) {
		BinaryTree bt = new BinaryTree();
		int[] input = {10,5,12,4,7};
		TreeNode node;
		for(int i =0;i<input.length;i++){
			node = new TreeNode(input[i],null,null);
			bt.insert(node);
			
		}
		//bt.midOrder(bt.getTree().getNode());
		LinkedList<Integer> path = new LinkedList<Integer>(); 
		int exceptsum = 22;//要求的和
		int currentsum = 0;//当前值初始化为0
		findPath(bt.getTree().getNode(),exceptsum,currentsum,path);
	}
	
	public static void findPath(TreeNode root,int exceptsum,int currentsum,LinkedList path){
		if(root == null){
			return;
		}
		currentsum +=root.getKey();//当前值加上本次遍历的节点的值
		path.add(root.getKey());//把当前节点加入到路径中去
		boolean isLeaf = (root.getLeftchild()==null)&&(root.getRightchild()==null);//判断当前节点是否是叶子节点
		if(currentsum==exceptsum &&isLeaf ){//如果当前值等于要求的和并且当前节点是叶子节点,则打印路径
			System.out.println(path);
		}
		if(root.getLeftchild()!=null){
			findPath(root.getLeftchild(),exceptsum,currentsum,path);
		}
		if(root.getRightchild()!=null){
			findPath(root.getRightchild(),exceptsum,currentsum,path);
		}
		currentsum-=root.getKey();//要返回父节点时,减去本次便利的节点的值
		path.removeLast();//要返回父节点时,把该节点从路径中删除
	}

}
/*
 * 以下代码为二叉树的构建
 * 
 * */
class TreeNode{
	private int key;
	private TreeNode leftchild;
	private TreeNode rightchild;
	public TreeNode(int key,TreeNode leftchild,TreeNode rightchild){
		this.key=key;
		this.leftchild=leftchild;
		this.rightchild=rightchild;
	}
	public int getKey() {
		return key;
	}
	public void setKey(int key) {
		this.key = key;
	}
	public TreeNode getLeftchild() {
		return leftchild;
	}
	public void setLeftchild(TreeNode leftchild) {
		this.leftchild = leftchild;
	}
	public TreeNode getRightchild() {
		return rightchild;
	}
	public void setRightchild(TreeNode rightchild) {
		this.rightchild = rightchild;
	}
	
}
class Tree{
	private TreeNode node;

	public TreeNode getNode() {
		return node;
	}

	public void setNode(TreeNode node) {
		this.node = node;
	}
	
}
class Queue{
	private LinkedList<TreeNode> list = new LinkedList<TreeNode>();
	public void enQueue(TreeNode node){
		list.add(node);
	}
	public TreeNode outQueue(){
		return list.removeFirst();
	}
	public boolean isempty(){
		if(list.size()==0){
			return true;
		}
		return false;
	}
}
class BinaryTree{
	private Tree tree;
	public Tree getTree() {
		return tree;
	}
	public void setTree(Tree tree) {
		this.tree = tree;
	}
	private Queue queue;
	public BinaryTree(){
		tree = new Tree();
	}
	public void insert(TreeNode node){
		if(tree.getNode()==null){
			tree.setNode(node);
			return;
		}
		else{
			 queue = new Queue();
			queue.enQueue(tree.getNode());
			while(!queue.isempty()){
				TreeNode temp = queue.outQueue();
				if(temp.getLeftchild()==null){
					temp.setLeftchild(node);
					return;
				}
				else if(temp.getRightchild()==null){
					temp.setRightchild(node);
					return;
				}
				else{
					queue.enQueue(temp.getLeftchild());
					queue.enQueue(temp.getRightchild());
				}
			}
		}
	}
	public void midOrder(TreeNode node){		
		if(node!=null){
		midOrder(node.getLeftchild());		
		System.out.println(node.getKey());
		midOrder(node.getRightchild());
		}
	}
}

输出结果:

[10, 5, 7]
[10, 12]

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值