• 树之105 Construct Binary Tree from Preorder and Inorder Traversal


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

    参考链接:https://blog.csdn.net/qq_36172443/article/details/81105258

         https://www.lintcode.com/problem/clone-binary-tree/description

         https://www.cnblogs.com/phdeblog/p/9309219.html

    首先你得理解如何递归建立一颗二叉树,然后才能理解本题。网上有很多解法都是通过变化中序遍历和前序续遍历的index来求解本题,这样的解法很容易弄错。如何变化index这是一个难点,该解法通过数组copy避免了计算index。

        public TreeNode buildTree(int[] pre, int[] in) {
            if (pre.length == 0) {
                return null;
            }
            int i = 0;
            for (; i < in.length; i++) {
                if (pre[0] == in[i]) {
                   break;
                }
            }
            TreeNode node = new TreeNode(pre[0]);
            //[1,i] [0,i-1]
            //[i+1,length-1] [i+1,length-1]
            node.left = buildTree(
                    Arrays.copyOfRange(pre, 1, i + 1),
                    Arrays.copyOfRange(in, 0, i));
            node.right = buildTree(
                    Arrays.copyOfRange(pre, i + 1, pre.length),
                    Arrays.copyOfRange(in, i + 1, in.length));
            return node;
    
        }
    

      

    加油啦!加油鸭,冲鸭!!!
  • 相关阅读:
    Maximal Square
    Count Complete Tree Nodes
    Rectangle Area
    Implement Stack using Queues
    Basic Calculator
    Invert Binary Tree
    Summary Ranges
    Basic Calculator II
    Majority Element II
    Kth Smallest Element in a BST
  • 原文地址:https://www.cnblogs.com/clarencezzh/p/10208740.html
Copyright © 2020-2023  润新知