剑指offer---04-树--重建二叉树(前序和中序)

 
题意
根据前序和中序返回遍历的结果
 
分析
---写一个函数,有前序遍历和中序遍历数组,有两个范围返回树的根节点。
前序遍历:开始节点一定是根节点,找到根节点在中序的位置,那么那个位置左边是左子树,右边是右子树。
前序遍历也是根节点,左子树和右子树。
 
代码
/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if(pre==null||in==null)return null;
        return returnRoot(pre,0,pre.length-1,in,0,in.length-1);
    }
    
    public TreeNode returnRoot(int[] pre,int preS,int preE,int[] in,int inS,int inE){
        if(preS>preE||inS>inE)return null;
        //前序遍历的第一个节点就是根节点
        TreeNode root = new TreeNode(pre[preS]);
        if(preS == preE)return root;
        //找到根节点的位置,然后进行左右子树的创建,找到左右子树的位置
        //下面这一步是用来找根节点在中序遍历中的位置的。
        int rootValue = pre[preS];
        int rootPos = 0;
        for(int i=inS;i<=inE;i++){
            if(rootValue == in[i]){
                rootPos = i;
                break;
            }
        }
        int length = rootPos-inS;//用来创建左子树的长度
        root.left = returnRoot(pre,preS+1,preS+length,in,inS,inS+length-1);
        root.right = returnRoot(pre,preS+length+1,preE,in,inS+length+1,inE);
        return root;
    }
}

猜你喜欢

转载自www.cnblogs.com/buptyuhanwen/p/9376926.html
今日推荐