重建二叉树

要求:根据提供的先序和中序遍历结果,输出后序遍历结果

public class Test{
	public static void main(String[] args) {
		int[] preOrder = {1, 2, 3, 4, 5, 6};
		int[] midOrder = {3, 2, 4, 1, 6, 5};
		printPostOrder(preOrder, midOrder);
	}
	 

	static void  printPostOrder(int[] preOrder, int[] midOrder) {
		Node root = constructTree(preOrder, 0, preOrder.length, midOrder, 0, midOrder.length-1);
		postOrder(root);
	}
	
	//preStart-preEnd一定等于midStart-midEnd
	static private Node constructTree(
			int[] preOrder, int preStart, int preEnd,
			int[] midDorder, int midStart, int midEnd) {
                if (preStart > preEnd || midStart > midEnd)
                    return null;

		Node node = new Node();
		node.val = preOrder[preStart];
		int local = 0;
		for (int i=midStart; i<=midEnd; i++)
			if (midDorder[i] == node.val) {
				local = i;
				break;
			}
		int len1 = local - midStart;
		node.LChild = constructTree(preOrder, preStart+1, preStart+len1,
					midDorder, midStart, local-1);
		node.RChild = constructTree(preOrder, preStart+len1+1, preEnd,
				midDorder, local+1, midEnd);
		return node;
	}
	
	static class Node {
        int val;
        Node LChild;
        Node RChild;
	}
	
	static private void postOrder(Node _root) {
        if (_root != null) {
            postOrder(_root.LChild);
            postOrder(_root.RChild);
            System.out.print(_root.val);
        }
    }
}
posted @ 2017-06-11 22:13  被罚站的树  阅读(106)  评论(0编辑  收藏  举报