根据一棵树的前序遍历与中序遍历构造二叉树以及后序与中序遍历序列构造二叉树
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
前序:根节点 + 左子树的前序遍历 + 右子树的前序遍历
中序:左子树的中序遍历 + 根节点 + 右子树的中序遍历
在前序中是最方便找根节点的,而在中序中,找到根节点后根节点就意味着他的左边就是他的左子树,右边就是右子树。
那么解题的思路就出来了,先在前序中找根节点,找到根节点后,在中序中找到根节点所在的下标并记录下来,中序中根节点的下标就代表着左子树的个数,根据根节点将左子树与右子树区分开。将区分开的左子树放入一个新的数组中,这一块需要用到Arrays . copyOfRange()这个方法在原中序数组和前序上截取下来,将这个新数添加到root中。循环调用这个方法,直到这个数组的大小为0时,递归终止,右边也是同样的道理。最后返回root。
后序与中序遍历序列构造二叉树与 已知前序与中序遍历序列构造二叉树 的思想是一样的,只是一个是前序,一个是后序,只要上面的关于 已知前序与中序遍历序列构造二叉树的思想明白了,那下面的这个你也就会了。
前序与中序遍历序列构造二叉树代码:
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder.length == 0) {
return null;
}
int rootValue = preorder[0];
int leftCount;
for (leftCount = 0; leftCount < inorder.length; leftCount++) {
if (inorder[leftCount] == rootValue) {
break;
}
}
TreeNode root = new TreeNode(rootValue);
int[] leftPreorder = Arrays.copyOfRange(preorder, 1, 1 + leftCount);//左子树的前序
int[] leftInorder = Arrays.copyOfRange(inorder, 0, leftCount);//左子树的中序
root.left = buildTree(leftPreorder, leftInorder);
int[] rightPreorder = Arrays.copyOfRange(preorder, 1 +leftCount,preorder.length);//右子树的前序
int[] rightInorder = Arrays.copyOfRange(inorder, leftCount + 1, inorder.length);//右子树的中序
root.right = buildTree(rightPreorder, rightInorder);
return root;
}
}
后序与中序遍历序列构造二叉树代码:
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder.length==0){
return null;
}
int rootVal = postorder[postorder.length-1];
int postCount;
for ( postCount = 0; postCount < inorder.length; postCount++) {
if(inorder[postCount] == rootVal){
break;
}
}
TreeNode root = new TreeNode(rootVal);
int[] leftInorder = Arrays.copyOfRange(inorder,0,postCount);
int[] leftPostorder = Arrays.copyOfRange(postorder,0,postCount);
root.left = buildTree(leftInorder,leftPostorder);
int[] rightInorder = Arrays.copyOfRange(inorder,postCount+1,inorder.length);
int[] rightPostorder = Arrays.copyOfRange(postorder,postCount,postorder.length-1);
root.right = buildTree(rightInorder,rightPostorder);
return root;
}
}