Construct Binary Tree from Preorder and Inorder Traversal

本文介绍如何根据给定的先序遍历和中序遍历构建二叉树的方法,并提供了一个C++实现示例。

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

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

Note:

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


以前写traversal的时候其实是死记硬背。。。谁在前谁在后,遇到这个题才这要搞懂。youtube有个人一步步给画了。不贴了

假设树 pre order为 a b c d e f g, 那么 a为root. 如果他的inorder 为 b c d a e f g 那么 bcd为左,def为右,然后递归的对左右做同样的操作。 


/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
    	return helper(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
    }

    TreeNode* helper(vector<int>& preorder, int pStart, int pEnd, vector<int>& inorder, int iStart, int iEnd){
    	if (pStart>pEnd)
    		return NULL;
    	if (pStart==pEnd)
    		return new TreeNode(preorder[pStart]);

    	int rootInd;
    	for (int i=iStart; i<=iEnd; i++){
    		if (inorder[i]==preorder[pStart]){
    			rootInd=i;
    			break;
    		}
    	}
    	TreeNode* root=new TreeNode(preorder[pStart]);
    	int leftLen=rootInd-iStart;
    	root->left=helper(preorder, pStart+1, pStart+leftLen, inorder, iStart, rootInd-1);
    	root->right=helper(preorder, pStart+leftLen+1, pEnd, inorder, rootInd+1, iEnd);
    	return root;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值