zoukankan      html  css  js  c++  java
  • [LeetCode]Construct Binary Tree from Preorder and Inorder Traversal

    题目描述:(链接)

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

    解题思路:

     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         return buildTree(begin(preorder), end(preorder), begin(inorder), end(inorder));
    14     }
    15     
    16 private:
    17     TreeNode *buildTree(vector<int>::iterator p_first, vector<int>::iterator p_last, 
    18                         vector<int>::iterator i_first, vector<int>::iterator i_last) {
    19         if (p_first == p_last) return nullptr;
    20         if (i_first == i_last) return nullptr;
    21         
    22         auto root = new TreeNode(*p_first);
    23         auto inRootPos = find(i_first, i_last, *p_first);
    24         auto leftSize = distance(i_first, inRootPos);
    25         
    26         root->left = buildTree(next(p_first), next(p_first, leftSize + 1), i_first, next(i_first, leftSize));
    27         root->right = buildTree(next(p_first, leftSize + 1), p_last, next(inRootPos), i_last);
    28         
    29         return root;
    30     }
    31 };
  • 相关阅读:
    文件操作
    安全名词
    浏览器并发连接
    acm 2057
    acm 2072
    acm 2084
    acm 2044
    acm 2043
    acm 2032
    acm 2005
  • 原文地址:https://www.cnblogs.com/skycore/p/5038146.html
Copyright © 2011-2022 走看看