利用前序遍历和中序遍历构建二叉树 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
输入
[1,2],[1,2]
输出
{1,#,2}
示例2
输入
[1,2,3],[2,3,1]
输出
{1,2,#,#,3}
解题思路
每次利用前序遍历的根节点找到中序遍历中的根节点位置,然后将数组划分为左右子树两部分,继续进行遍历。
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int size = preorder.size();
return build(preorder, 0, size - 1, inorder, 0, size - 1);
}
TreeNode* build(vector<int>& preorder, int preStart, int preEnd,
vector<int>& inorder, int inStart, int inEnd) {
if(preStart > preEnd) return NULL;
//将前序遍历中的根节点的值创建为一个新的节点
TreeNode* root = new TreeNode(preorder[preStart]);
//如果仅剩根节点,直接返回
if(preStart == preEnd) return root;
//在中序遍历中,根据前序遍历找到根节点的位置
int rootIndex;
for(int i = inStart; i <= inEnd; i ++) {
if(preorder[preStart] == inorder[i]) {
rootIndex = i; //找到根节点位置后保存
break;
}
}
int length = rootIndex - inStart; //左子树的数组长度
root -> left = build(preorder, preStart + 1, preStart + length, inorder, inStart, rootIndex - 1);
root -> right = build(preorder, preStart + length + 1, preEnd, inorder, rootIndex + 1, inEnd);
return root;
}
};