标签:
题目:从一棵树的前序和中序遍历结果构建一棵树。
前序遍历结果的第一个结点是树的根节点;在中序遍历结果中,根节点的左边是树的左子树,右边是树的右子树。然后再重新确定左子树和右子树的范围,递归寻找左子树和右子树的根节点。
TreeNode* buildSubTree(vector<int>& preorder,vector<int>& inorder,int pre_start,int pre_end,int in_start,int in_end){ if(pre_start>pre_end) return NULL; TreeNode* root=new TreeNode(preorder[pre_start]); int i=in_start; while(i<=in_end&&inorder[i]!=preorder[pre_start]) i++; int pos=i; int leftlength=pos-in_start; root->left=buildSubTree(preorder,inorder,pre_start+1,pre_start+leftlength,in_start,pos-1); root->right=buildSubTree(preorder,inorder,pre_start+leftlength+1,pre_end,pos+1,in_end); return root; } TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { if(preorder.size()==0||inorder.size()==0) return NULL; return buildSubTree(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1); }
这里需要注意的是递归终止条件:pre_start>pre_end.
Construct Binary Tree from Preorder and Inorder Traversal
标签:
原文地址:http://www.cnblogs.com/summerkiki/p/5471133.html