#sicily#1003.计算二叉查找树的高度
2016-12-30 11:31
288 查看
来源:http://soj.sysu.edu.cn/show_problem.php?pid=1003&cid=2511
考点:用先序遍历和中序遍历查找二叉树的高度
例如:一个二叉查找树其先序遍历为:16, 10, 4, 15, 23 ; 中序遍历为 4, 10, 15, 16, 23,则其高度为2(假定空树高度为-1,只有根节点的数高度为0)
对于每个测试用例,
第一行是节点个数n,第二行是key值的先序遍历,第三行是key值的中序遍历
2
3
4 5 6
4 5 6
5
6 4 8 9 10
4 6 8 9 10
3
2.不建树,而通过已知的先序、中序从而知道每一层二叉树的下一层是什么,然后统计层数。
思路1是能马上想到的, 思路2比较难想,而且想到跟寻找下一层跟统计层数混在一起写,可能比较难写。故用了思路1。
考点:用先序遍历和中序遍历查找二叉树的高度
题意
Description
给定一个二叉查找树,要求计算其高度,每个二叉查找树将给出先序与中序的遍历。例如:一个二叉查找树其先序遍历为:16, 10, 4, 15, 23 ; 中序遍历为 4, 10, 15, 16, 23,则其高度为2(假定空树高度为-1,只有根节点的数高度为0)
Input
第一行输入测试用例个数。对于每个测试用例,
第一行是节点个数n,第二行是key值的先序遍历,第三行是key值的中序遍历
Output
对于每个测试用例,用一行输出树的高度Sample Input
Copy sample input to clipboard2
3
4 5 6
4 5 6
5
6 4 8 9 10
4 6 8 9 10
Sample Output
23
思路
1.最直观的思路:建树,然后递归搜索查找树的高度。2.不建树,而通过已知的先序、中序从而知道每一层二叉树的下一层是什么,然后统计层数。
思路1是能马上想到的, 思路2比较难想,而且想到跟寻找下一层跟统计层数混在一起写,可能比较难写。故用了思路1。
源代码
#include <iostream> #include <vector> #include <algorithm> using namespace std; vector<int> preOrder; vector<int> inOrder; int getPos(int val, const vector<int>& v) { for(int i = 0;i < v.size(); i++) { if (val == v[i]) return i; } return -1; } struct node { int val; node* left; node* right; node(int value): val(value), left(NULL), right(NULL){} }; int getHeight(node* root) { if (root->left == NULL && root->right == NULL) { return 1; } else if (root->left == NULL && root->right != NULL) { return 1 + getHeight(root->right); } else if (root->left != NULL && root->right == NULL) { return 1 + getHeight(root->left); } else { return 1 + max(getHeight(root->left), getHeight(root->right)); } } node* buildTree(int rootArr, int inOrderPosBegin, int inOrderPosEnd) { if (inOrderPosBegin == inOrderPosEnd) return NULL; if(inOrderPosEnd - inOrderPosBegin == 1) { return new node(preOrder[rootArr]); } else { node* tmp = new node(preOrder[rootArr]); tmp -> left = buildTree(rootArr+1,inOrderPosBegin, getPos(preOrder[rootArr], inOrder)); tmp->right = buildTree(rootArr + getPos(preOrder[rootArr], inOrder) - inOrderPosBegin + 1, getPos(preOrder[rootArr], inOrder) + 1, inOrderPosEnd); return tmp; } } int main() { int n, tmp; cin >> n; while(n--) { preOrder.clear(); inOrder.clear(); int m; cin >> m; for(int i = 0; i < m; i++) { cin >> tmp; preOrder.push_back(tmp); } for(int i = 0; i < m; i++) { cin >> tmp; inOrder.push_back(tmp); } node* head = buildTree(0, 0, inOrder.size()); cout << getHeight(head) - 1<< endl; } return 0; }
相关文章推荐
- sicily 计算二叉查找树的高度 期末考试题
- 1002. 计算二叉查找树的高度
- 二叉查找树的结点插入,查找,删除,计算二叉树的高度
- [C++日常小题] 计算二叉查找树的高度
- 计算文本高度
- Android 计算软键盘高度
- 用Model来计算cell的高度
- iOS开发之功能模块--计算高度Demo探究手稿
- ScrollView嵌套ListView只显示一行之计算的高度不正确的解决办法
- 优化UITableViewCell高度计算的那些事
- iOS cell嵌套webView,准确计算高度!
- 优化UITableViewCell高度计算
- Sicily 1814. 日期计算问题
- 关于滚动布局中的Listview的高度重新计算
- ScrollView与ListView合用(正确计算Listview的高度)的问题解决
- C++计算二叉树的节点数和高度
- 优化UITableViewCell高度计算的那些事
- scrollview中嵌入listview动态计算listview的高度
- label自动换行并且计算其高度
- scroll嵌套多个listview,listview中的TextView超过一行,只计算 一行高度