zoukankan      html  css  js  c++  java
  • Leetcode(106)-从中序与后序遍历序列构造二叉树

    根据一棵树的中序遍历与后序遍历构造二叉树。

    注意:
    你可以假设树中没有重复的元素。

    例如,给出

    中序遍历 inorder = [9,3,15,20,7]
    后序遍历 postorder = [9,15,7,20,3]

    返回如下的二叉树:

        3
       / 
      9  20
        /  
       15   7

    思路:和上一篇的由前序和中序类似。后序遍历的顺序是左右根,所以最后一个元素一定是根节点。再在中序遍历中找到这个节点的位置,则根节点左边是左子树的中序遍历结果,右边是右子树的中序遍历结果。在后序遍历中同样可以分为两个部分,分别对应左子树的后序遍历结果和右子树的遍历结果。再递归就可以得到最终的二叉树分布

      TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) 
     {
         int size = inorder.size();
         if(size==0 || postorder.empty())
             return NULL;
         int r=postorder.back();
         TreeNode *root =new TreeNode(r);
         int p=0;
         for(;p<size;p++)
         {
             if(inorder[p]==r)
                 break;
         }
         vector<int> in_left,in_right,post_left,post_right;
         for(int i=0;i<size;i++)
         {
             if(i<p)
             {
                 in_left.push_back(inorder[i]);
                 post_left.push_back(postorder[i]);
             }
             else if(i>p)
             {
                 in_right.push_back(inorder[i]);
                post_right.push_back(postorder[i-1]);//这里要注意位置
             }
         }
         root->left = buildTree(in_left,post_left);
         root->right = buildTree(in_right,post_right);
         return root;
     }
  • 相关阅读:
    poj3348 Cow
    poj3348 Cow
    日常。。。强行续
    日常。。。又又续
    日常。。。又又续
    日常。。。又续
    内存检索
    MyLayer MyScene
    冒泡排序
    Array数组的排序与二分查字法
  • 原文地址:https://www.cnblogs.com/mini-coconut/p/9089699.html
Copyright © 2011-2022 走看看