重建二叉树-剑指Offer

重建二叉树

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

思路

  1. 先序遍历的第一个节点是中序遍历的根节点
  2. 从中序遍历中找先序遍历的那个根节点,然后切开左右子树,用递归函数分别构造左右子树

代码

public class Solution04 {
	// 重建二叉树
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if (pre == null || in == null) {
        	return null;
        }
        return ConstructCore(pre, 0, pre.length -1, in, 0, in.length -1);
    }
	public TreeNode ConstructCore(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn) {
		int rootValue = pre[startPre];
		TreeNode root = new TreeNode(rootValue);
		root.left = null;
		root.right = null;
		
		if (startPre == endPre && startIn == endIn) {
			return root;
		}
		
		int leftLen = 0;
		int rootIn = startIn;
		while (startIn <= endIn && in[startIn] != rootValue) {
			startIn++;
			leftLen++;
		}
		int leftPreEnd = startPre + leftLen;
		if (leftLen > 0) {
			// 构建左子树
			root.left = ConstructCore(pre, startPre + 1, leftPreEnd, in, rootIn, startIn - 1);
		}
		if (leftLen < endPre - startPre) {
			//构建右子树
			root.right = ConstructCore(pre, leftPreEnd + 1, endPre, in, startIn + 1, endIn);
		}
		return root;
	}
	


}
class TreeNode {
	int val;
	TreeNode left;
	TreeNode right;
	TreeNode(int x) { val = x; }
}
posted @ 2016-06-22 21:03  RosenDing  阅读(231)  评论(0编辑  收藏  举报