加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

LeetCode:Construct Binary Tree from Preorder and Inorder Tra

发布时间:2020-12-14 02:41:16 所属栏目:大数据 来源:网络整理
导读: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. 题意:根据二叉树的先序和中序遍历的结果来构建

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.

题意:根据二叉树的先序和中序遍历的结果来构建此二叉树(二叉树中不包含值相同的节点)

解题思路:在数据结构课程中我们知道可以由二叉树的先序和中序或者中序和后序的遍历结果来构建此二叉树,具体步骤如何呢?我们举个具体的例子来分析。


如图,我们可以分三步:1、将先序遍历序列的第一个值作为根节点(如将6作为根节点);2、从中序遍历中寻找第一步的节点在此序列的下标(如6在此下标为2);3、根据下标更新遍历序列,递归构建此根节点的左右子树,进入步骤1.


//p_s、p_e表示在先序遍历数组中的起始位置和结束位置,i_s、i_e表示中序遍历数组的起始位置和结束位置
TreeNode* buildNodes(vector<int>& preorder,int p_s,int p_e,vector<int>&inorder,int i_s,int i_e)
{
	if (p_s > p_e || i_s > i_e)
		return NULL;

	//先序遍历的第一个节点是作为根节点
	TreeNode* node = new TreeNode(preorder[p_s]);
	
	//从中序遍历中找到该节点的位置
	int nodeIndex = i_s;
	while (nodeIndex<=i_e && preorder[p_s] != inorder[nodeIndex])
		nodeIndex++;
	
	//在中序遍历中,计算该节点离此次遍历起始位置的长度
	int leftLen = nodeIndex - i_s;
	//构建左子树,更新遍历范围
	node->left = buildNodes(preorder,p_s + 1,p_s + leftLen,inorder,i_s,nodeIndex - 1);

	//构建右子树,更新遍历范围
	node->right = buildNodes(preorder,p_s + leftLen + 1,p_e,nodeIndex + 1,i_e);

	return node;
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读