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     }
  • 相关阅读:
    算法提高---概率计算
    全排列
    算法提高 最小方差生成树
    【洛谷】P1040 加分二叉树
    SPAF模板
    Bellman-Ford算法(有向图)
    Floyd算法
    Dijkstra算法
    蓝桥杯算法提高 递推求值 【矩阵快速幂】
    【动态规划】数字分组I
  • 原文地址:https://www.cnblogs.com/mike442144/p/3439959.html
Copyright © 2011-2022 走看看