• 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     }
  • 相关阅读:
    sql获取当天零点
    byte[]和InputStream的相互转换
    ResultSet获取记录条数
    Java:String和Date、Timestamp之间的转换
    查询表中blob字段的大小
    Oracle中start with...connect by子句的用法
    oracle创建序列,并插入记录
    关于使用JSONArray.fromObject()方法和引入net.sf.json包所需要的jar包支持
    css来控制img正方形自适应
    上下固定中间自适应
  • 原文地址:https://www.cnblogs.com/mike442144/p/3439959.html
Copyright © 2020-2023  润新知