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

https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

这个题的思想其实很容易理解,我们的前序遍历数组中,第一个元素肯定是当前这棵树的根节点,然后我们再中序遍历中找到这个根节点,那么相当于就把中序遍历数组划分成了左子树中序遍历数组和右子树中序遍历数组了。然后回到前序遍历数组,我们在中序遍历数组中知道了左子树的节点个数,然后我们就从在前序遍历数组的第二个元素开始计数,直到数量与左子树节点个数相同。那么我们同样将前序遍历数组分割成了[1,i] [i+1,结尾],前者为左子树的前序遍历,后者为右子树的前序遍历,然后我们递归去做,并且返回根节点。

结束条件就是传入的数组为空,就意味着这个树里面没有节点,返回null。

/**
 * 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.length == 0 || inorder.length == 0){
            return null;
        }
        TreeNode root = new TreeNode(preorder[0]);
        int i = 0;
        for(; i < inorder.length; i++){
            if(inorder[i] == preorder[0]){
                break;
            }
        }
        root.left = buildTree(Arrays.copyOfRange(preorder,1,i+1),Arrays.copyOfRange(inorder,0,i));
        root.right = buildTree(Arrays.copyOfRange(preorder,i+1,preorder.length),Arrays.copyOfRange(inorder,i+1,inorder.length));
        return root;
    }
}
原文地址:https://www.cnblogs.com/ZJPaang/p/12935635.html