剑指offer-----重构二叉树

/**
 * 剑指offer面试题6:重构二叉树
 * 
 * 题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历结果中都不含重复的数字。
 * 
 * 思路:根据前序遍历序列的第一个数字创建根结点,接下来在中序遍历序列中找到根结点的位置,这样就可以确定左、右子树结点的
 * 数量。在前序遍历和中序遍历的序列中划分左、右子树结点的值,然后递归调用,分别构建它的左右子树。
 * 
 * 例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建出下图的二叉树并输出他的根节点。
 *                     1
 *                   /   \
 *                  2     3
 *                 /     / \
 *                4     5   6
 *                 \        /
 *                 7        8
 */
public class CreateBinaryTree {
	
	/**
	 * 重建二叉树
	 */
	public static TreeNode reConstructBinaryTree(int[] pre,int[] in) {
		//参数合法性检验
		if(pre == null || in == null || pre.length != in.length) {
			return null;
		}
		return reConstructBinaryTree(pre, 0, pre.length-1, in, 0, in.length-1);
	}

	/**
	 * @param pre 前序遍历序列
	 * @param startPre 前序遍历开始位置
	 * @param endPre 前序遍历结束位置
	 * @param in 中序遍历序列
	 * @param startIn 中序遍历开始位置
	 * @param endIn 中序遍历结束位置
	 * @return 构建的树的根节点
	 */
	public static TreeNode reConstructBinaryTree(int[] pre,int startPre,int endPre,
			int[] in,int startIn,int endIn) {
		//开始位置大于结束位置说明已经处理到叶节点了
		if(startPre > endPre || startIn >endIn) {
			return null;
		}
		//当前的根结点
		TreeNode root = new TreeNode(pre[startPre]);
		for (int index = startIn; index <=endIn; index++) {
			if(in[index] == pre[startPre]) {
				//构建左子树
				//左子树对应的前序遍历的位置在pre[startPre+1,startPre+index-startIn]
				//左子树对应的中序遍历的位置在in[startIn,index-1]
				root.left = reConstructBinaryTree(pre, startPre+1, startPre+index-startIn, in, startIn,index-1);
				//构建右子树
				//右子树对应的前序遍历的位置在pre[index-startIn+startPre+1, endPre]
				//右子树对应的中序遍历的位置在in[index+1, endIn]
				root.right = reConstructBinaryTree(pre, index-startIn+startPre+1, endPre, in, index+1, endIn);
				break;
			}
		}
		return root;
	}
	
	//中序遍历递归打印
	public static void printInOrder(TreeNode node) {
		if(node != null) {
			printInOrder(node.left);
			System.out.print(node.val+" ");
			printInOrder(node.right);
		}
	}
	
	//前序遍历递归打印
	public static void printPreOrder(TreeNode node) {
		if(node != null) {
			System.out.print(node.val+" ");
			printPreOrder(node.left);
			printPreOrder(node.right);
		}
	}
	
	public static void main(String[] args) {
        int[] pre={1,2,4,7,3,5,6,8};
        int[] in={4,7,2,1,5,3,8,6};
        printInOrder(reConstructBinaryTree(pre, in));
        System.out.println();
        System.out.println("-------------------------");
        printPreOrder(reConstructBinaryTree(pre, in));
	}

	
}

class TreeNode {
	int val;
	TreeNode left;
	TreeNode right;
	TreeNode(int x) { 
		val = x; 
	}
}

猜你喜欢

转载自blog.csdn.net/yb1020368306/article/details/81366849
今日推荐