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     }
  • 相关阅读:
    在window10系统下安装redis
    Dubbo 基础用法
    vue处理对象值改变时dom值没有跟着变化的问题
    KMP算法
    Leetcode 502 IPO
    vue页面无法正常渲染的问题
    vue锚点双向绑定
    JavaScript克隆一个对象
    el-table刷新后table出现抖动现象
    el-table组件去掉滚动条的问题
  • 原文地址:https://www.cnblogs.com/hhhhan1025/p/10723478.html
Copyright © 2011-2022 走看看