Redian新闻
>
rebuild a tree from inorder and level order
avatar
rebuild a tree from inorder and level order# JobHunting - 待字闺中
K*g
1
请问有谁知道这题的思路?多谢了
avatar
i*e
2
你意思是从文件读取树,用 inorder 来重建树对吧?

【在 K******g 的大作中提到】
: 请问有谁知道这题的思路?多谢了
avatar
y*e
3

是BST嘛?假设是BST。
6
/ \
4 8
/ \ / \
1 5 7 9
inorder是 1 4 5 6 7 8 9
levelorder是 6 4 8 1 5 7 9
6
/ \
4 8
/ / \
1 7 9
inorder是 1 4 6 7 8 9
levelorder是 6 4 8 1 7 9
注意到,在 levelorder 中, INDEX (parent) < INDEX (node)。
解法思路如下:
1、取 levelorder 的第一个,作为 root。在 inorder 里面,小于 root 的值,是为
left sub tree。在 inorder 里面,大于root 的值,是为 right sub tree。
2、在 levelorder 里面找寻第一个值 n,使得 n < root && INDEX(n) >
INDEX(root)

【在 K******g 的大作中提到】
: 请问有谁知道这题的思路?多谢了
avatar
K*g
4
Got it. 多谢了!

【在 y*********e 的大作中提到】
:
: 是BST嘛?假设是BST。
: 6
: / \
: 4 8
: / \ / \
: 1 5 7 9
: inorder是 1 4 5 6 7 8 9
: levelorder是 6 4 8 1 5 7 9
: 6

avatar
g*d
5
好像是从本版抄的.
node * restore(int pre[], int in[], int N)
{
if (!N) return NULL;
int * it = std::lower_bound(in, in + N, *pre);
assert(it != in + N && !(*pre < *it));
int index = it - in;
node * root = new node(*pre);
root->left = restore(pre + 1, in, index);
root->right = restore(pre + index + 1, in + index + 1, N - index - 1);
return root;
}
avatar
c*w
6
仅仅靠Index(Parent)子树的根啊?
比如:
int inorderSeq[]= {2,4,9,8,3,1,6,7,5};
int levorderSeq[]={1,2,5,3,6,4,7,8,9};
When you go to the first element of level order 1, it is the root, 1
separate the in order seq into two parts. The left part is its left subtree
[2,4,9,8,3], the right part is its right subtree[6,7,5]. The program goes to
the left subtree, we need find which one is the root of left subtree.
The root of left subtree is the one with the minimum level

【在 y*********e 的大作中提到】
:
: 是BST嘛?假设是BST。
: 6
: / \
: 4 8
: / \ / \
: 1 5 7 9
: inorder是 1 4 5 6 7 8 9
: levelorder是 6 4 8 1 5 7 9
: 6

avatar
j*l
7
看题不仔细~
不是pre + in

【在 g******d 的大作中提到】
: 好像是从本版抄的.
: node * restore(int pre[], int in[], int N)
: {
: if (!N) return NULL;
: int * it = std::lower_bound(in, in + N, *pre);
: assert(it != in + N && !(*pre < *it));
: int index = it - in;
: node * root = new node(*pre);
: root->left = restore(pre + 1, in, index);
: root->right = restore(pre + index + 1, in + index + 1, N - index - 1);

avatar
K*g
8
这个解答好像有问题,试试level>3的tree,就不对了

【在 y*********e 的大作中提到】
:
: 是BST嘛?假设是BST。
: 6
: / \
: 4 8
: / \ / \
: 1 5 7 9
: inorder是 1 4 5 6 7 8 9
: levelorder是 6 4 8 1 5 7 9
: 6

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。