Fork me on github

105 从前序与中序遍历序列构造二叉树

/*
 * @lc app=leetcode.cn id=105 lang=java
 *
 * [105] 从前序与中序遍历序列构造二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder== null || preorder.length <= 0){
            return null;
        }

        int preL = 0, preR = preorder.length - 1;
        int inL = 0, inR = inorder.length - 1;
        return helper(preorder, preL, preR, inorder, inL, inR);
    }

    public TreeNode helper(int[] preorder, int preL, int preR, int[] inorder, int inL, int inR){
        if(preL > preR || inL > inR || preR > preorder.length || inR > inorder.length){
            return null;
        }
        int rootIndex = 0;
        TreeNode root = new TreeNode(preorder[preL]);
        for(int i = inL; i <= inR; i++){
            if(inorder[i] == root.val){
                rootIndex = i;
                break;
            }
        }

        root.left = helper(preorder, preL + 1, preL + (rootIndex - inL), inorder, inL, rootIndex - 1);
        root.right = helper(preorder, preL + (rootIndex - inL) + 1, preR, inorder, rootIndex + 1, inR);

        return root;
    }
}
// @lc code=end


posted @ 2020-08-24 23:58  zjy4fun  阅读(145)  评论(0编辑  收藏  举报