Leetcode105 & 106. Construct Binary Tree from Preorder and Inorder Traversal

根据前序遍历和中序遍历构建一个二叉树
我真是一个可恨的菜逼

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    public TreeNode build(int[] preorder, int[] inorder, int pre_left, int pre_right, int in_left, int in_right){
        TreeNode root = new TreeNode(preorder[pre_left]);
        
        if(pre_left == pre_right){
            return root;
        }
        
        int i;
        for(i= 0; i <= in_right; i++){
            if(inorder[i] == preorder[pre_left])break;
        }
        
        if(i - 1 >= in_left)
            root.left = build(preorder,inorder, pre_left + 1, pre_right + (i - in_left), in_left, i-1);
        if(i + 1 <= in_right)
            root.right = build(preorder, inorder, pre_left + (i - in_left) + 1, pre_right, i+1, in_right);
        return root;
    }
    
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder.length == 0 || inorder.length == 0){
            return null;
        }
        return build(preorder, inorder, 0, preorder.length-1, 0, inorder.length-1);
    }
}

然后是根据前序遍历和后序遍历构建一个二叉树

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    public TreeNode build(int[] inorder, int[] postorder, int in_left, int in_right, int post_left, int post_right){
        TreeNode root = new TreeNode(postorder[post_right]);
        
        if(in_left == in_right)return root;
        
        int i;
        for(i = in_left; i <= in_right; i++){
            if(root.val == inorder[i])break;
        }
        
        
        if(i-1 >= in_left)
            root.left = build(inorder,postorder,in_left, i-1,post_left, post_left + (i-1 - in_left));
        if(i+1 <= in_right)
            root.right = build(inorder,postorder, i+1,in_right,post_right - in_right + i,post_right-1);
        return root;
    }
    
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder.length == 0 || postorder.length == 0)return null;
        return build(inorder, postorder, 0, inorder.length-1, 0, postorder.length-1);
    }
}

你可能感兴趣的:(ACM之路)