zoukankan      html  css  js  c++  java
  • leetcode105—— 从前序与中序遍历序列构造二叉树

     1 /*
     2  * @lc app=leetcode.cn id=105 lang=cpp
     3  *
     4  * [105] 从前序与中序遍历序列构造二叉树
     5  */
     6 
     7 // @lc code=start
     8 /**
     9  * Definition for a binary tree node.
    10  * struct TreeNode {
    11  *     int val;
    12  *     TreeNode *left;
    13  *     TreeNode *right;
    14  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    15  * };
    16  */
    17 class Solution {
    18 public:
    19     /*
    20     1)前序数组的第一个元素为根节点,根据根节点可将中序数组划分为左子树中序列表和右子树中序数组
    21     2)又因为一棵树的中序数组长度与前序数组长度大小相同,所以可以根据长度划分前序数组为左右子树前序数组
    22     3)对于根的左右结点,递归调用即可
    23     */
    24     TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
    25        if(preorder.empty()||inorder.empty()) return nullptr;
    26 
    27        TreeNode *root=new TreeNode(*preorder.begin());//begin返回的是迭代器,要取值的话加 *
    28 
    29        auto it=find(inorder.begin(),inorder.end(),*preorder.begin());
    30 
    31        vector<int> inleft(inorder.begin(),it); //左闭右开,所以inleft不包含it这个值
    32        vector<int> inright(it+1,inorder.end());//加 1是为了跳过根节点
    33        int sz=inleft.size();
    34        vector<int> preleft(preorder.begin()+1,preorder.begin()+1+sz);
    35        vector<int> preright(preorder.begin()+1+sz,preorder.end());
    36        root->left=buildTree(preleft,inleft);
    37        root->right=buildTree(preright,inright);
    38 
    39        return root;
    40 
    41     }
    42 };
    43 // @lc code=end
  • 相关阅读:
    controller传到页面的值出现乱码
    Uncaught SyntaxError: Unexpected identifier
    No mapping found for HTTP request with URI xxx/resources/js/jquery.min.js...
    jQuery,Ajax和json
    idea中tomcat启动但是访问不了localhost:8080页面
    不允许有匹配 "[xX][mM][lL]" 的处理指令目标。
    11.流程控制之if判断
    10.可变,不可变数据类型
    Python基础
    文件处理
  • 原文地址:https://www.cnblogs.com/yaodao12/p/13934428.html
Copyright © 2011-2022 走看看