其他分享
首页 > 其他分享> > LeetCode 全题解计划之树专题:LC 105(五)

LeetCode 全题解计划之树专题:LC 105(五)

作者:互联网

LC 105. 从前序与中序遍历序列构造二叉树(M)

题目描述

举个栗子

解题思路

代码来了

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder.length <= 0 || inorder.length <= 0) {
            return null;
        }
        if (preorder.length == 1 && inorder.length == 1) {
            return new TreeNode(preorder[0]);
        }
        return build(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
    }
    private TreeNode build(int[] preorder, int preLeft, int preRight, int[] inorder, int inLeft, int inRight) {
        if (preLeft > preRight || inLeft > inRight) {
            return null;
        }

        int rootValue = preorder[preLeft];
        int index = -1;
        for (int i = inLeft; i <= inRight; i++) {
            if (rootValue == inorder[i]) {
                index = i;
                break;
            }
        }

        int leftNum = index - inLeft;
        TreeNode root = new TreeNode(rootValue);
        root.left = build(preorder, preLeft + 1, preLeft + leftNum, inorder, inLeft, index - 1);
        root.right = build(preorder, preLeft + leftNum + 1, preRight, inorder, index + 1, inRight);
        return root;
    }
}

标签:preorder,遍历,TreeNode,LC,int,题解,之树,preLeft,inorder
来源: https://blog.csdn.net/fangzhan666/article/details/122208933