Construct Binary Tree from Preorder and Inorder Traversal

问题描述

Given preorder and inorder traversal of a tree, construct the binary tree.

 

解决思路

首先确定根节点,然后确定左右子树的节点数目。依次递归即可。

假设输入的序列均合法。

 

程序

public class BuildTreeFromPreorderAndInorder {
	public TreeNode buildTree(int[] preorder, int[] inorder) {
		if (preorder == null || inorder == null || preorder.length == 0
				|| preorder.length != inorder.length) {
			return null;
		}
		int len = preorder.length;
		TreeNode root = buildHelper(preorder, 0, len - 1, inorder, 0, len - 1);
		return root;
	}

	private TreeNode buildHelper(int[] preorder, int pre_start, int pre_end,
			int[] inorder, int in_start, int in_end) {
		// bound
		if (pre_start > pre_end || in_start > in_end) {
			return null;
		}

		int rootVal = preorder[pre_start];
		TreeNode root = new TreeNode(rootVal);
		// find root-val in inorder list
		int i = 0;
		for (; i <= in_end; i++) {
			if (inorder[i] == rootVal) {
				break;
			}
		}

		int leftLen = i - in_start;
		root.left = buildHelper(preorder, pre_start + 1, pre_start + leftLen,
				inorder, in_start, i - 1);
		root.right = buildHelper(preorder, pre_start + leftLen + 1, pre_end,
				inorder, i + 1, in_end);

		return root;
	}
}

 

Follow up

如果给定的是中序和后序遍历序列,如何构建二叉树?

解决思路是类似的。

 

程序

public class BuildTreeFromInorderAndPostorder {
	public TreeNode buildTree(int[] inorder, int[] postorder) {
		if (inorder == null || postorder == null || inorder.length == 0
				|| inorder.length != postorder.length) {
			return null;
		}
		int len = inorder.length;
		TreeNode root = buildHelper(inorder, 0, len - 1, postorder, 0, len-1);
		return root;
	}

	private TreeNode buildHelper(int[] inorder, int in_start, int in_end, int[] postorder,
			int post_start, int post_end) {
		if (in_start > in_end || post_start > post_end) {
			return null;
		}
		
		int rootVal = postorder[post_end];
		TreeNode root = new TreeNode(rootVal);
		
		int i = in_start;
		for (; i <= in_end; i++) {
			if (inorder[i] == rootVal) {
				break;
			}
		}
		
		int leftLen = i - in_start;
		root.left = buildHelper(inorder, in_start, i-1, postorder, post_start, post_start+leftLen-1);
		root.right = buildHelper(inorder, i+1, in_end, postorder, post_start+leftLen, post_end - 1);
		
		return root;
	}
}

  

posted @ 2015-07-18 11:04  Chapter  阅读(153)  评论(0编辑  收藏  举报