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     }
  • 相关阅读:
    js变量类型
    js词法分析
    ORACLE 查找字段在哪些表里存在
    主外键约束的关闭和启用
    pl/sql developer 编码格式设置(转)
    WIN7 Net Configuration Assistant打不开
    Kettle 连接失败 Oracle 数据库报 ora-12505 的解决方法(转)
    正则表达式30分钟入门教程(转)
    设置程序的多个入口,进行动态的显示
    应用多入口配置
  • 原文地址:https://www.cnblogs.com/mike442144/p/3439959.html
Copyright © 2011-2022 走看看