一个二叉树的每个节点,要么有两个孩子,要么没有孩子。给你一个数组 int pre[],该数组代表这个二叉树的前序遍历序列;数组 char preLN[] 代表相应的节点是不是叶子节点,'L'表示是叶子节点,'N'表示非叶子节点。要求,恢复出原来的二叉树。
思路:
可以采用和 “从前序遍历序列恢复BST(线性时间复杂度)” 相似的思想来做这道题。
代码如下:
struct Node{
int key; Node* left; Node* right;
Node(int k, Node* l=NULL, Node* r=NULL): key(k), left(l), right(r){};
};
Node* construct(int pre[], char preLN[], int size, int* idx)
// size: the length of pre and preLN
// idx: point to the elements in pre and preLN currently under examination
{
if(*idx < size)
{
Node* node = new Node(pre[*idx]);
if( preLN[*idx] == 'L' ){
*idx = *idx + 1;
return node;
}
else{
*idx = *idx + 1;
node->left = construct(pre, preLN, size, idx);
node->right = construct(pre, preLN, size, idx);
return node;
}
}
return NULL;
}