[leetcode] Construct Binary Tree from Preorder and Inorder Traversal

本文介绍了一种通过给定的先序遍历和中序遍历构建二叉树的方法。利用递归算法实现,首先找到根节点,然后划分左子树和右子树,重复该过程直到所有节点被构建完成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

From : https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

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

Note:
You may assume that duplicates do not exist in the tree.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTreeRecursive(vector<int>& pre, vector<int>& in, int s1, int e1, int s2, int e2) {
        if(s1>e1) return NULL;
        if(s1==e1) return new TreeNode(pre[s1]);
        
        TreeNode* root = new TreeNode(pre[s1]);
        int index=s2, rootV=root->val;
        while(rootV != in[index]) index++;
        
        root->left = buildTreeRecursive(pre, in, s1+1, s1+index-s2, s2, index-1);
        root->right = buildTreeRecursive(pre, in, s1+index-s2+1, e1, index+1, e2);
        return root;
    }

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        if(preorder.size()==0 || inorder.size()==0) return NULL;
        int start = 0, end = preorder.size()-1;
        return buildTreeRecursive(preorder, inorder, start, end, start, end);
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值