对于一棵树or子树而言,假设其根节点为root,那么其左孩子一定是其左子树的根节点,而这个节点在前序遍历中对应的就是其左子树序列的第一个节点。对于root的右孩子也同理,其右孩子一定是其右子树序列的第一个节点。那么在前序序列中,如何找到对于root而言的左子树和右子树的分界呢?这里就要借助中序遍历序列了,由中序序列很容易就得知左子树和右子树的长度。通过计算就可得到在前序序列中左右子树的分界点。
class Solution {
//对于一棵树or子树而言,假设其根节点为root,那么其左孩子一定是其左子树的根节点,而这个节点在前序遍历中对应的就是其左子树序列的第一个节点。对于root的右孩子也同理,其右孩子一定是其右子树序列的第一个节点。那么在前序序列中,如何找到对于root而言的左子树和右子树的分界呢?这里就要借助中序遍历序列了,由中序序列很容易就得知左子树和右子树的长度。通过计算就可得到在前序序列中左右子树的分界点。
public TreeNode mybuildTree(int[] preorder,int preleft,int preright,HashMap<Integer,Integer> inmap,int inleft,int inright){
if(preleft>preright||inleft>inright)
return null;
int root_index=inmap.get(preorder[preleft]);
int value=preorder[preleft];
TreeNode root=new TreeNode(value);
int leftTree_rear=root_index-inleft+preleft;//计算前序序列中左子树的最后一个节点在序列中的位置,然后右子树的第一个节点位置就是该值+1
root.left=mybuildTree(preorder,preleft+1,leftTree_rear,inmap,inleft,root_index-1);
root.right=mybuildTree(preorder,leftTree_rear+1,preright,inmap,root_index+1,inright);
return root;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
int prelen=preorder.length;
int inlen=inorder.length;
HashMap<Integer,Integer> inmap=new HashMap<Integer,Integer>();
for(int i=0;i<inlen;i++){//将中序遍历的值与下标的对应存入哈希,便于查找
inmap.put(inorder[i],i);
}
return mybuildTree(preorder,0,prelen-1,inmap,0,inlen-1);
}
}
对于树或者子树,假设其根节点为root,其左孩子一定是其左子树后序序列最后一个节点,其右孩子一定是其右子树后序序列最后一个节点,那么如何在给定的整棵树的后序序列中找到对应节点的左子树区间和右子树区间呢?这里就要借助中序序列来计算左子树的长度,得到左右子树对应的区间。
class Solution {
//对于树或者子树,假设其根节点为root,其左孩子一定是其左子树后序序列最后一个节点,其右孩子一定是其右子树后序序列最后一个节点,那么如何在给定的整棵树的后序序列中找到对应节点的左子树区间和右子树区间呢?这里就要借助中序序列来计算左子树的长度,得到左右子树对应的区间。
public TreeNode mybuildTree(int[] postorder,int postleft,int postright,HashMap <Integer,Integer> inmap,int inleft,int inright){
if(postleft>postright||inleft>inright)
return null;
int value=postorder[postright];
int root_index=inmap.get(value);//查找该节点在中序序列中的下标
TreeNode root=new TreeNode(value);
int lefttree_rear=root_index-1-inleft+postleft;//计算该节点对应左子树后序序列中最后一个节点在后序序列中的下标,然后该节点右子树后序序列第一个节点所对应的位置就是该值+1
root.left=mybuildTree(postorder,postleft,lefttree_rear,inmap,inleft,root_index-1);
root.right=mybuildTree(postorder,lefttree_rear+1,postright-1,inmap,root_index+1,inright);
return root;
}
public TreeNode buildTree(int[] inorder, int[] postorder) {
int postlen=postorder.length;
int inlen=inorder.length;
HashMap <Integer,Integer> inmap= new HashMap <Integer,Integer>();
for(int i=0;i<inlen;i++)//将中序序列值与下标的对应存入哈希中,便于查找。
inmap.put(inorder[i],i);
return mybuildTree(postorder,0,postlen-1,inmap,0,inlen-1);
}
}