LeetCode--105/106. Construct Binary Tree from Inorder/Preorder and Postorder Traversal

这两个题目思路如出一辙,算法原来也写过详细的博客,参考这两个1.https://blog.csdn.net/To_be_to_thought/article/details/84668630

2.https://blog.csdn.net/To_be_to_thought/article/details/84674266

代码集中贴一下:

class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return recursion(inorder,preorder,0,0,inorder.length);
    }
    
    
    public static TreeNode recursion(int[] inorder,int[] preorder,int preStart,int inStart,int n)
    {
        if(n<=0)
            return null;
        int rootValue=preorder[preStart];
        TreeNode p=new TreeNode(rootValue);
        int i=0;
        while(i<n && inorder[i+inStart]!=rootValue)
            i++;
        p.left=recursion(inorder,preorder,preStart+1,inStart,i);
        p.right=recursion(inorder,preorder,preStart+i+1,inStart+i+1,n-1-i);
        return p;
    }
}
class Solution {
    public static TreeNode buildTree(int[] inorder, int[] postorder) {
        return recursion(inorder,postorder,0,0,inorder.length);
    }
    
    public static TreeNode recursion(int[] inorder,int[] postorder,int inStart,int postStart,int n)
    {
        if(n<=0)
            return null;
        int rootValue=postorder[postStart+n-1];
        TreeNode p=new TreeNode(rootValue);
        int i=0;
        while(i<n && inorder[i+inStart]!=rootValue)
            i++;
        p.left=recursion(inorder,postorder,inStart,postStart,i);
        p.right=recursion(inorder,postorder,inStart+i+1,postStart+i,n-i-1);
        return p;
    }
}

猜你喜欢

转载自blog.csdn.net/To_be_to_thought/article/details/84675371