zoukankan      html  css  js  c++  java
  • 树之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;
    
        }
    

      

    加油啦!加油鸭,冲鸭!!!
  • 相关阅读:
    HDU3516 树的构造
    poj1160 post office
    poj1260 pearls
    POJ 3709 K-Anonymous Sequence
    HDU2829
    HDU 3480 division
    HDU3507 print artical
    HDU2490 parade
    HDU3530 子序列
    HDU3415
  • 原文地址:https://www.cnblogs.com/clarencezzh/p/10208740.html
Copyright © 2011-2022 走看看