当前位置:首页 > 开发 > 编程语言 > Java > 正文

java-从先序遍历和中序遍历重建二叉树

发表于: 2012-01-17   作者:bylijinnan   来源:转载   浏览:
摘要: public class BuildTreePreOrderInOrder { /** * Build Binary Tree from PreOrder and InOrder * _______7______ / \ __10__ ___2 / \ / 4

public class BuildTreePreOrderInOrder {

	/**
	 * Build Binary Tree from PreOrder and InOrder
	 *  _______7______
       /              \
    __10__          ___2
   /      \        /
   4       3      _8
            \    /
             1  11
             
	 */
	public static void main(String[] args) {
		BuildTreePreOrderInOrder build=new BuildTreePreOrderInOrder();
		int[] preOrder = {7,10,4,3,1,2,8,11};
		int[] inOrder = {4,10,3,1,7,11,8,2};

		Node root=build.buildTreePreOrderInOrder(preOrder,0,preOrder.length-1,inOrder,0,preOrder.length-1);
		build.preOrder(root);
		System.out.println();
		build.inOrder(root);
	}

	public Node buildTreePreOrderInOrder(int[] preOrder,int begin1,int end1,int[] inOrder,int begin2,int end2){
		if(begin1>end1||begin2>end2){
			return null;
		}
		int rootData=preOrder[begin1];
		Node head=new Node(rootData);
		int divider=findIndexInArray(inOrder,rootData,begin2,end2);
		int offSet=divider-begin2-1;
		Node left=buildTreePreOrderInOrder(preOrder,begin1+1,begin1+1+offSet,inOrder,begin2,begin2+offSet);
		Node right=buildTreePreOrderInOrder(preOrder,begin1+offSet+2,end1,inOrder,divider+1,end2);
		head.left=left;
		head.right=right;
		return head;
	}
	
	public int findIndexInArray(int[] a,int x,int begin,int end){
		for(int i=begin;i<=end;i++){
			if(a[i]==x)return i;
		}
		return -1;
	}
	public void preOrder(Node n){
		if(n!=null){
			System.out.print(n.val+",");
			preOrder(n.left);
			preOrder(n.right);
		}
	}
	public void inOrder(Node n){
		if(n!=null){
			inOrder(n.left);
			System.out.print(n.val+",");
			inOrder(n.right);
		}
	}
	
	class Node{
		Node left;
		Node right;
		int val;

	public Node(int val){
		this.val=val;
	}
		public Node getLeft(){
			return left;
		}

	public Node getRight(){
			return right;
		}

	public int getVal(){
			return val;
		}


	}
}


java-从先序遍历和中序遍历重建二叉树

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号