• LeetCode


    Construct Binary Tree from Preorder and Inorder Traversal

    2014.1.8 00:59

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

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

    Solution:

      preorder traversal = root, left, right;

      inorder traversal = left, root, right;

      Thus the first element in the preorder sequence is the root. Find it in the inorder sequence and you know where the left and right subtrees are. Do this procedure recursively and the job is done.

      Time and space complexities are both O(n), where n is the number of nodes in the tree. The space complexity comes from the local parameters passed in function calls.

    Accepted code:

     1 // 1AC, excellent!!!
     2 /**
     3  * Definition for binary tree
     4  * struct TreeNode {
     5  *     int val;
     6  *     TreeNode *left;
     7  *     TreeNode *right;
     8  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     9  * };
    10  */
    11 class Solution {
    12 public:
    13     TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
    14         // IMPORTANT: Please reset any member data you declared, as
    15         // the same Solution instance will be reused for each test case.
    16         return recoverTree(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1);
    17     }
    18 private:
    19     TreeNode *recoverTree(vector<int> &preorder, vector<int> &inorder, int l1, int r1, int l2, int r2) {
    20         if(l1 > r1){
    21             return nullptr;
    22         }
    23         
    24         if(l2 > r2){
    25             return nullptr;
    26         }
    27         
    28         TreeNode *root = new TreeNode(preorder[l1]);
    29         int i;
    30         
    31         for(i = l2; i <= r2; ++i){
    32             if(inorder[i] == root->val){
    33                 break;
    34             }
    35         }
    36         
    37         root->left = recoverTree(preorder, inorder, l1 + 1, (l1 + 1)  + (i - 1 - l2), l2, i - 1);
    38         root->right = recoverTree(preorder, inorder, r1 - (r2 - i - 1), r1, i + 1, r2);
    39         
    40         return root;
    41     }
    42 };
  • 相关阅读:
    swagger的使用说明
    Springboot组件:全局异常处理
    打金?工作室?账号被封?游戏灰黑产离我们有多近
    如何用Pygame制作简单的贪吃蛇游戏
    函数式编程
    py接口自动化基础
    py类,实例
    高级特性
    css中margin负值的运用
    css多行文本溢出显示省略号
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3509986.html
Copyright © 2020-2023  润新知