作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我遇到了一个我真正感兴趣的问题,但我不确定我是否完全理解如何完成手头的任务:设计一种算法,从两个 n 长序列构造二叉树,已知是同一二叉树的中序和后序遍历。
到目前为止我已经完成了这么多。下面是到目前为止我的(相关)代码,但是我也希望能够识别不存在二叉树的序列。我不知道如何检查这一点。有人可以给我一个正确的方向吗?
node* build_tree(int in[], int inStart, int inEnd,
int post[], int postStart, int postEnd) {
if(inStart > inEnd || postStart > postEnd)
return NULL;
int rootValue = post[postEnd];
node *tNode = new_node(rootValue);
// find the index of this node in in-order traversal
int inIndex = search(in, inStart, inEnd, rootValue);
// Using index in in-order traversal, construct left and right subtrees
tNode->left = build_tree(in, inStart, inIndex-1, post, postStart, postStart+inIndex-(inStart+1));
tNode->right = build_tree(in, inIndex+1, inEnd, post, postStart + inIndex - inStart, postEnd - 1);
return tNode;
}
// Function to find index of value in arr[start...end]
// The function assumes that value is present in in[]
int search(int arr[], int start, int end, int value) {
int i;
for(i = start; i < end; i++) {
if(arr[i] == value)
return i;
}
return i;
}
// function that allocates a new node with the
// given data and NULL left and right pointers
node* new_node(int data) {
node* n = (node*)malloc(sizeof(node));
n->data = data;
n->left = NULL;
n->right = NULL;
return n;
}
最佳答案
据我所知,当 时,二叉树对于给定序列是不可能的,
1) 两个序列长度不同 -- 我们可以检查数组长度
2) 中序序列中查找后序值失败 -- 搜索函数应修改为在搜索失败时返回负值,而不是返回 i(在 for 循环之后)
3) 给定的序列不代表同一棵树的后序和中序 -- 按照 Gene 的建议遍历树并检查序列
关于从中序和后序遍历构造二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26725640/
序 大家好呀,我是summo,这次来写写我在上班空闲(摸鱼)的时候做的一个小网站的事。去年阿里云不是推出了个活动嘛,2核2G的云服务器一年只要99块钱,懂行的人应该知道这个价格在业界已经是非常良心了
我尝试根据给定的级别顺序(BFS 顺序)构造 BST。我知道这是可能的,但我不知道我该怎么写。问题是我必须使用 BFS 序列。所以,我不能在这里使用递归,我必须迭代地编写我的程序......我发现这有
我是一名优秀的程序员,十分优秀!