首先,我想说明这不是一个功课.我正在准备面试并遇到这个问题.我想我们可以通过
in-order和
level-order遍历的定义. :-).
例如:
50
/ \
10 60
/ \ / \
5 20 55 70
/ / \
51 65 80
The in-order and level-order traversal of the above tree are:
5, 10, 20, 50, 51, 55, 60, 65, 70, 80
50, 10, 60, 5, 20, 55, 70, 51, 65, 80
我的想法:
(1) traversal the level-order array to find out the first element
which appears in the in-order array. We call this element as current
root.(2) find the index of current root in the in-order array. The in-order
array is separated by the index. The left side of the in-order array
is the left sub-tree of the current root and the right side of the
in-order array is the right sub-tree of the current root.(3) update the in-order array as its left side and then go to step 1.
(4) update the in-order array as its right side and then go to step 2.
以上面的树为例.
06001
谁能帮我验证我的解决方案?
如果给另一个人真的很感激.
最佳答案 我认为你走在正确的轨道上.下面是我使用您的数据制定的工作代码.
/*
//construct a bst using inorder & levelorder traversals.
//inorder - 5, 10, 20, 50, 51, 55, 60, 65, 70, 80
//levelorder - 50, 10, 60, 5, 20, 55, 70, 51, 65, 80
50
/ \
10 60
/ \ / \
5 20 55 70
/ / \
51 65 80
*/
struct node *construct_bst3(int inorder[], int levelorder[], int in_start, int in_end)
{
static int levelindex = 0;
struct node *nnode = create_node(levelorder[levelindex++]);
if (in_start == in_end)
return nnode;
//else find the index of this node in inorder array. left of it is left subtree, right of this index is right.
int in_index = search_arr(inorder, in_start, in_end, nnode->data);
//using in_index from inorder array, constructing left & right subtrees.
nnode->left = construct_bst3(inorder, levelorder, in_start, in_index-1);
nnode->right = construct_bst3(inorder, levelorder, in_index+1, in_end);
return nnode;
}