`

算法 给定二叉树前序和中序序列重建二叉树

阅读更多

给定二叉树前序和中序序列重建二叉树

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

 思路:前序序列第一个肯定为root,设值为N,则在中序序列中N所在位置左边的肯定是左子树的元素,右边的是右子树的元素,因此,递归找root即可

public class Solution {
        public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
	         return reConstructBinaryTree0(pre, 0, pre.length, in, 0, in.length);
        }
	
	public TreeNode reConstructBinaryTree0(int [] pre, int preStart, int preEnd, int [] in, int inStart, int inEnd) {
		if (preStart >= preEnd) { // way out
			return null;
		}
		int rootIndex = indexOf(in, inStart, inEnd, pre[preStart]);
		TreeNode root = new TreeNode(pre[preStart]);
		int leftPreStart = preStart + 1;
		int leftPreEnd = leftPreStart + (rootIndex - inStart);
		int leftInStart = inStart;
		int leftInEnd = rootIndex;
                // 构建左子树
		root.left = reConstructBinaryTree0(pre, leftPreStart, leftPreEnd, in, leftInStart, leftInEnd);
		
		int rightPreStart = leftPreEnd;
		int rightPreEnd = preEnd;
		int rightInStart = rootIndex + 1;
		int rightInEnd = inEnd;
                // 构建右子树
		root.right = reConstructBinaryTree0(pre, rightPreStart, rightPreEnd, in, rightInStart, rightInEnd);
		return root;
	}
	
        // 找下标
	public int indexOf(int[] array, int start, int end, int value) {
		for (int i = start; i < end; i++) {
			if (array[i] == value) {
				return i;
			}
		}
		return -1;
	}
}

 

0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics