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 };
  • 相关阅读:
    谈谈关于MVP模式中V-P交互问题
    Delphi MVC模 2
    Delphi MVC模式 1
    Java长整除问题
    Java中Scanner类的简单用法
    Java中throw和throws的区别
    Java必须掌握的运算符
    Java编程多重循环
    Java实现三种简单的排序
    使用Java向properties存数据
  • 原文地址:https://www.cnblogs.com/skycore/p/5038146.html
Copyright © 2011-2022 走看看