zoukankan      html  css  js  c++  java
  • LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal 由前序和中序遍历建立二叉树 C++

    Given preorder and inorder traversal of a tree, construct the binary tree.

    Note:
    You may assume that duplicates do not exist in the tree.

    For example, given

    preorder = [3,9,20,15,7]
    inorder = [9,3,15,20,7]

    Return the following binary tree:

        3
       / 
      9  20
        /  
       15   7

    前序、中序遍历得到二叉树,可以知道每一次前序新数组的第一个数为其根节点。在中序遍历中找到根节点对应下标,根结点左边为其左子树,根节点右边为其右子树,再根据中序数组中的左右子树个数,找到对应的前序数组中的左右子树新数组。设每次在中序数组中对应的位置为i,则对应的新数组为:

    前序新数组:左子树[pleft+1,pleft+i-ileft],右子树[pleft+i-ileft+1,pright]

    中序新数组:左子树[ileft,i-1],右子树[i+1,iright]  C++

     1 TreeNode* buildTree(vector<int>& preorder,int pleft,int pright,vector<int>& inorder,int ileft,int iright){
     2         if(pleft>pright||ileft>iright)
     3             return NULL;
     4         int i=0;
     5         for(i=ileft;i<=iright;i++){
     6             if(preorder[pleft]==inorder[i])
     7                 break;
     8         }
     9         TreeNode* cur=new TreeNode(preorder[pleft]);
    10         cur->left=buildTree(preorder,pleft+1,pleft+i-ileft,inorder,ileft,i-1);
    11         cur->right=buildTree(preorder,pleft+i-ileft+1,pright,inorder,i+1,iright);
    12         return cur;
    13     }
    14     TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
    15         return buildTree(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
    16     }
  • 相关阅读:
    浅谈软件开发项目的质量控制
    分布式系统稳定性模式
    正确使用 Volatile 变量
    我和 OI 的一些故事
    NOIP2020 退役记
    博弈论基础入门
    [HAOI2008]硬币购物(容斥/背包DP)
    [CF] 1307F Cow and Vacation(思维/贪心)
    [noi.ac 模拟赛8] c(容斥/DP)
    [noi.ac 模拟赛9] A.出征准备(同余最短路)
  • 原文地址:https://www.cnblogs.com/hhhhan1025/p/10723478.html
Copyright © 2011-2022 走看看