zoukankan      html  css  js  c++  java
  • Construct Binary Tree from Inorder and Postorder Traversal

    题目:

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

    跟之前的通过先序遍历和中序遍历构建二叉树一样,有个区别是,这次的根结点每次都从后序列表中从后向前扫。代码:

     1     TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         int idx=postorder.size()-1;
     5         return buildTree(inorder,postorder,0,inorder.size(),&idx);
     6     }
     7     TreeNode *buildTree(vector<int> &inorder,vector<int> &postorder,int start,int len,int* idx){
     8         if(!len || idx<0) return NULL;
     9         TreeNode* root=(TreeNode*)malloc(sizeof(TreeNode));
    10         root->val=postorder[*idx];
    11         root->left=NULL;
    12         root->right=NULL;
    13         int i=start;
    14         while(i-start<len){
    15             if(inorder[i]==root->val) break;
    16             i++;
    17         }
    18         
    19         if(i-start+1<len){
    20             root->right=buildTree(inorder,postorder,i+1,start+len-i-1,&(--*idx));
    21         }
    22         if(i>start){
    23             root->left=buildTree(inorder,postorder,start,i-start,&(--*idx));
    24         }
    25         return root;
    26     }
  • 相关阅读:
    东拼西凑 vim配置-更新
    oh-my-zsh
    switch变种玩法
    每天一个linux命令(5):rm 命令
    每天一个linux命令(4):mkdir命令
    每天一个linux命令(3):pwd命令
    ES6学习之let
    Window.scrollTo()
    如何调整滚动条的样式
    移动端实现滚动的四种方案
  • 原文地址:https://www.cnblogs.com/mike442144/p/3439961.html
Copyright © 2011-2022 走看看