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

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

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

    For example, given

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

    Return the following binary tree:

        3
       / 
      9  20
        /  
       15   7

    中序、后序遍历得到二叉树,可以知道每一次新数组的最后一个数为当时子树的根节点,每次根据中序遍历的根节点的左右两边确定左右子树,再对应后序的左右子树,不停递归得到根节点,可以建立二叉树。每次由循环得到根节点在中序数组中坐标i

    由中序遍历知:每一次inorder的左子树范围[ileft,i-1],右子树范围[i+1,iright]

    由后序遍历知:每一次postorder的左子树范围[pleft,pleft+i-ileft-1],右子树范围[pleft+i-ileft,pright-1]。C++

     1 TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
     2         return buildTree(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
     3     }
     4     
     5     TreeNode* buildTree(vector<int>& inorder,int ileft,int iright,vector<int>& postorder,int pleft,int pright){
     6         if(ileft>iright||pleft>pright)
     7             return NULL;
     8         TreeNode* root=new TreeNode(postorder[pright]);
     9         int i=0;
    10         for(i=ileft;i<=iright;i++){
    11             if(inorder[i]==postorder[pright])
    12                 break;
    13         }
    14         root->left=buildTree(inorder,ileft,i-1,postorder,pleft,pleft+i-ileft-1);
    15         root->right=buildTree(inorder,i+1,iright,postorder,pleft+i-ileft,pright-1);
    16         return root;
    17     }
  • 相关阅读:
    操作系统——理论知识
    BEGIN-4 Fibonacci数列
    BEGIN-3 圆的面积
    面向对象三大特征之一:多态
    面向对象三大特征之二:继承
    package---包
    面向对象三大特征之一:封装
    关键字:This(上)
    无参构造与有参构造
    面向对象
  • 原文地址:https://www.cnblogs.com/hhhhan1025/p/10713560.html
Copyright © 2011-2022 走看看