• 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     }
  • 相关阅读:
    关于 js 下载PDF文件时
    vue3.0 学习
    iOS
    bootstrap treeview
    SVN版本管理
    js框架
    正则表达式
    如何让安卓手机在电脑上同步显示(MX4 Pro为例)
    mysql 中文乱码
    ADO.NET 数据库连接池大小
  • 原文地址:https://www.cnblogs.com/hhhhan1025/p/10713560.html
Copyright © 2020-2023  润新知