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.

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

    Analyse: We can see from the pic above that the left of the pivot element of Preorder sequence in Inorder sequence is the left subtree of this element, and the right part is the right subtree of this element. 

    Runtime: 64ms.

    Recursion
     1 /**
     2  * Definition for a binary tree node.
     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.size() == 0) return NULL;
    14         return build(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1);
    15     }
    16     TreeNode* build(vector<int>& preorder, int preLeft, int preRight, vector<int>& inorder, int inLeft, int inRight){
    17         if(preLeft > preRight) return NULL; //when will this case appear
    18         
    19         TreeNode* root = new TreeNode(preorder[preLeft]);
    20         if(preLeft == preRight) return root;
    21         
    22         //find the position of root(preorder[preLeft]) in inorder sequence
    23         int index = 0;
    24         for(; index < inorder.size(); index++){
    25             if(inorder[inLeft + index] == preorder[preLeft]) break;
    26         }
    27         
    28         root->left = build(preorder, preLeft + 1, preLeft + index, inorder, inLeft, inLeft + index - 1);
    29         root->right = build(preorder, preLeft + index + 1, preRight, inorder, inLeft + index + 1, inRight);
    30         
    31         return root;
    32     }
    33 };

  • 相关阅读:
    控制台日志输入到文件指定文件中
    flutter环境搭建坑一
    hybridapp/webapp的前端UI框架推荐
    hybrid app、web app与native app工具
    浏览记录
    HTML5跨平台APP越来越火,工具也越来越多。我推荐一个开发平台(一款工具)----DCloud
    学个p-nan isnan . isna isnull
    学个p-np.triu(m, k),np.tirl()
    实验五 plsql基础
    实验四-数据插入、更新、删除
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4687223.html
Copyright © 2011-2022 走看看