您的位置:首页 > 其它

#sicily#1003.计算二叉查找树的高度

2016-12-30 11:31 288 查看
来源:http://soj.sysu.edu.cn/show_problem.php?pid=1003&cid=2511

考点:用先序遍历和中序遍历查找二叉树的高度

题意

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 clipboard

2

3

4 5 6

4 5 6

5

6 4 8 9 10

4 6 8 9 10

Sample Output

2

3

思路

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: