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

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

    Note:
    You may assume that duplicates do not exist in the tree.

    题意:知道二叉树的前序遍历和中序遍历,重新构建出二叉树。

    算法:(略),代码如下:

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
    13         if(preorder.empty()||inorder.empty())  return NULL;
    14         return build(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
    15     }
    16     TreeNode  *build(vector<int> &preorder,int l,int r,vector<int> &inorder,int ll,int rr)
    17     {
    18         if(l>r||ll>rr)  return NULL;
    19         TreeNode* root=new TreeNode(0);
    20         root->val=preorder[l];
    21         if(l==r)  return root;
    22         int mid=0;
    23         for(int i=ll;i<=rr;i++)
    24         {
    25             if(inorder[i]==preorder[l])
    26             {
    27                 mid=i;
    28                 break;
    29             }
    30         }
    31         int midd=mid-ll+l;
    32         root->left=build(preorder,l+1,midd,inorder,ll,mid-1);
    33         root->right=build(preorder,midd+1,r,inorder,mid+1,rr);
    34         return root;
    35     }
    36 };
  • 相关阅读:
    Dom之标签增删操作
    Dom实例:数据自增、搜索框及跑马灯
    Dom选择器及操作文本内容
    Tkinter单选框及滚动条
    Tkinter颜色方案举例
    TKinter之窗口美化 窗口大小、图标等
    TKinter之文本域与多窗口
    TKinter之菜单
    JavaScript 基本语法
    TKinter的常用组件
  • 原文地址:https://www.cnblogs.com/sqxw/p/4001056.html
Copyright © 2011-2022 走看看