LeetCode 105. 从前序与中序遍历序列构造二叉树

另一个同源的题目:LeetCode 106. 从中序与后序遍历序列构造二叉树


思路都一样,只是找root的方式不同。

cpp 复制代码
class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        if(preorder.size() == 0)       return NULL;
        
        int rootVal = preorder[0];
        TreeNode* root = new TreeNode(rootVal);             //自己构建新树
        if(preorder.size() == 1)       return root;
        
        auto iter = find(inorder.begin(), inorder.end(), rootVal); 
        int pivot = iter - inorder.begin();     //找到根结点在中序数组的下标,作为后续分割依据
        
        //切割前序数组,将这层preorder的两个子序列传给下一层
        vector<int> leftPreOrder(preorder.begin() + 1, preorder.begin() + pivot + 1);
        vector<int> rightPreOrder(preorder.begin() + pivot + 1, preorder.end());
        
        //切割中序数组,将这层inorder的两个子序列传给下一层
        vector<int> leftInOrder(inorder.begin(), inorder.begin() + pivot);       //左边[)
        vector<int> rightInOrder(inorder.begin() + pivot + 1, inorder.end());    //右边(]

        root -> left = buildTree(leftPreOrder, leftInOrder);
        root -> right = buildTree(rightPreOrder, rightInOrder);
        return root;
    }
};
相关推荐
才鲸嵌入式1 小时前
C++相比于C语言增加了哪些概念?
c语言·c++·单片机·嵌入式·arm·面向对象·软件
周圣贤2 小时前
九尾狐编程语言新算法“超维时空演算体”
开发语言·算法
听风lighting5 小时前
1. C++ WebServer项目分享
linux·c语言·c++·设计模式·嵌入式·webserver
军训猫猫头5 小时前
100.Complex[]同时储存实数和虚数两组double的数组 C#例子
算法·c#·信号处理
2401_858286115 小时前
CD45.【C++ Dev】STL库的list的使用
开发语言·数据结构·c++·list
int型码农6 小时前
数据结构第八章(五)-外部排序和败者树
c语言·数据结构·算法·排序算法
好易学·数据结构6 小时前
可视化图解算法52:数据流中的中位数
数据结构·算法·leetcode·面试·力扣·笔试·牛客
dying_man6 小时前
LeetCode--35.搜索插入位置
算法·leetcode
暴躁茹7 小时前
C++中,std::async 一个用于异步编程的工具
开发语言·c++
点云SLAM7 小时前
PyTorch 中Tensor常用数据结构(int, list, numpy array等)互相转换和实战示例
数据结构·人工智能·pytorch·算法·list·numpy·tensor