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

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

思路🧐:

由题,前序可以知道根,中序能知道左右子树,那么我们可以进行第一次判断------根为3,左子树为9,右子树为15,20,7。可以利用递归,进行每个结点的判定,比如右子树为15,20,7,而前序顺序为20,15,7,所以可以判断右子树根为20,再一次用中序得出左子树为15,右子树为7,以此类推...

我们可以用rooti(中序数组下标)来切割左右子树rooti-1的范围是左子树,rooti+1的范围是右子树,rooti为需要构建的二叉树结点前序用于找根,中序用于划分,由此反复递归直到整棵树遍历完,就能够构造一颗二叉树了。

代码🔎:

c++ 复制代码
class Solution {
public:

    TreeNode* _build(vector<int>& preorder, vector<int>& inorder, int& previ, int inbegin,int inend)
    {
        if(inbegin > inend)
            return nullptr;

        int rooti = inbegin; //划分下标
        while(rooti <= inend)
        {
            //当[rooti]==[previ],表示找到根了
            if(preorder[previ] == inorder[rooti]) 
            {
                break;
            }
            rooti++; //没找到就++
        }
 	    //构建结点,并且++前序结点,方便下次rooti划分
        TreeNode* root = new TreeNode(preorder[previ++]);
	    //左子树范围在[begin,root-1]
        root->left = _build(preorder, inorder, previ, inbegin, rooti - 1);
        //右子树范围在[root+1,end]
        root->right = _build(preorder, inorder, previ, rooti + 1, inend);
        return root;
    }

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int i = 0;
        TreeNode* root = _build(preorder,inorder, i, 0, inorder.size() - 1);
        return root;
    }
};
相关推荐
Dream it possible!25 分钟前
LeetCode 面试经典 150_链表_反转链表 II(60_92_C++_中等)(头插法)
c++·leetcode·链表·面试
Theodore_10222 小时前
深度学习(3)神经网络
人工智能·深度学习·神经网络·算法·机器学习·计算机视觉
地平线开发者2 小时前
大模型 | VLA 初识及在自动驾驶场景中的应用
算法·自动驾驶
py有趣2 小时前
LeetCode学习之实现strStr()
学习·算法·leetcode
夏鹏今天学习了吗2 小时前
【LeetCode热题100(52/100)】课程表
算法·leetcode·职场和发展
祁思妙想2 小时前
【LeetCode100】--- 101.重排链表【思维导图+复习回顾】
算法·leetcode·链表
Dream it possible!2 小时前
LeetCode 面试经典 150_链表_随机链表的复制(59_138_C++_中等)
c++·leetcode·链表
文火冰糖的硅基工坊2 小时前
[人工智能-大模型-69]:模型层技术 - 计算机处理问题的几大分支:数值型性问题、非数值型问题?
算法·决策树·机器学习
OG one.Z3 小时前
05_逻辑回归
算法·机器学习·逻辑回归
lzptouch3 小时前
逻辑斯蒂回归(Logistic Regression)算法
算法·数据挖掘·回归