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

    题目:

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

    通过先序遍历和中序遍历构造二叉树。大概思路是递归的构造,因为先序遍历总是先访问根结点,所以很容易从先序列表中得到根,位于该结点右侧的就是子树,再由这个根结点从中序列表中找到,位于该值左侧的就是左子树,右侧的即为又子树。然后分别用同样的方法构建左、右子树,直到构造完成。代码:

     1     TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         int preIdx=0;
     5         return buildTree(preorder,inorder,&preIdx,0,inorder.size());
     6     }
     7     TreeNode* buildTree(vector<int>& preorder,vector<int>& inorder,int* preIdx,int inIdx,int inLen){
     8         if(preorder.size()==*preIdx||inLen==0) return NULL;
     9         TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
    10         root->val = preorder[*preIdx];
    11         root->left=NULL;
    12         root->right=NULL;
    13         int i=inIdx;
    14         while(i-inIdx<inLen){
    15             if(inorder[i]==root->val) break;
    16             i++;
    17         }
    18         if(i-inIdx>0&&*preIdx<preorder.size())//no left child
    19             root->left=buildTree(preorder,inorder,&(++*preIdx),inIdx,i-inIdx);
    20         if(inLen-(i-inIdx)-1>0&&*preIdx<preorder.size())//no right child
    21             root->right=buildTree(preorder,inorder,&(++*preIdx),i+1,inLen-(i-inIdx)-1);
    22         return root;
    23     }
  • 相关阅读:
    Python(九)之网络编程
    Bat命令
    Python(八)之函数
    RedHat下安装Python开发环境
    Redhat6.5安装DB2 Express-C版本
    Linux下字符集的安装
    Linux命令之stty
    AIX查看CPU、内存等信息
    stopManagedWebLogic.sh强制关闭Managed Server
    Keepalived + Nginx + Tomcat 的高可用负载均衡架构搭建
  • 原文地址:https://www.cnblogs.com/mike442144/p/3439959.html
Copyright © 2011-2022 走看看