zoukankan      html  css  js  c++  java
  • [Leetcode] Construct binary tree from preorder and inorder travesal 利用前序和中续遍历构造二叉树

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

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

    利用前序和中序遍历构造二叉树的思想与利用中序和后续遍历的思想一样,不同的是,全树的根节点为preorder数组的第一个元素,具体分析过程参照利用中序和后续构造二叉树。这两道题是从二叉树的前序遍历、中序遍历、后续遍历这三种遍历中选取两种方式构造二叉树,总的思路都是先确定全树根节点,然后在中序遍历中找到根节点,从而确定全树的左、右子树(题目要求没有重复元素,所以可以确定),最后以两子树为新的二叉树递归调用原函数。值得注意的是:利用三种遍历构造二叉树,要具备两条件,一、知道根节点、二,能区分左右子树,所以不能用前序遍历和后续遍历构造二叉树(不知道是否有大神可以)。代码如下

     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     {
    14         int len=preorder.size();
    15         return build(preorder,0,len-1,inorder,0,len-1);    
    16     }
    17 
    18     TreeNode *build(vector<int> &preorder,int preBeg,int preEnd,vector<int> &inorder,int inBeg,int inEnd)
    19     {
    20         if(preBeg>preEnd||inBeg>inEnd)  return NULL;
    21         TreeNode *root=new TreeNode(preorder[preBeg]);
    22 
    23         for(int i=0;i<inorder.size();++i)
    24         {
    25             if(inorder[i]==preorder[preBeg])
    26             {
    27                 root->left=build(preorder,preBeg+1,preBeg+i-inBeg,inorder,inBeg,i-1);
    28                 root->right=build(preorder,preBeg+i+1-inBeg,preEnd,inorder,i+1,inEnd);
    29             }
    30         }
    31         return root;
    32     }
    33 };
  • 相关阅读:
    练字的感悟
    关于简单
    全都是泡沫
    跟着电影环游世界
    12.8《印度之行》
    11.21派生类对基类的访问
    Linux,begin
    如何利用google
    回调函数
    原型对象
  • 原文地址:https://www.cnblogs.com/love-yh/p/6970409.html
Copyright © 2011-2022 走看看