|
楼主 |
发表于 2010-8-26 12:46:03
|
显示全部楼层
#include <iostream>
using namespace std;
class Node {
public:
Node(int);
void attL(Node *);
void attR(Node *);
int getH();
private:
int key;
Node *left, *right;
};
Node::Node(int k) {
key=k;
left=NULL;
right=NULL;
}
void Node::attL(Node *tree) {
if (left==0)
left=tree;
else
throw 'L';
}
void Node::attR(Node *tree) {
if (right==0)
right=tree;
else
throw 'R';
}
int Node::getH() {
int l,r;
if (left==0) 这里怎么改?
l=0;
else
l=(*left).getH();
if (right==0)
r=0;
else
r=(*left).getH();
if (l>r)
return l+1;
else
return r+1;
}
int main() {
Node n[9] = {0,1,2,3,4,5,6,7,8}; // construct nodes
for (int i = 1; i < 8; ++i) {
int root, subtree;
char LR;
cin >> root >> LR >> subtree; // get indices of the node and the root node
// of subtree, and whether it will become the
// left or right subtree.
try {
if (LR == 'L') n[root].attL(&n[subtree]);
else n[root].attR(&n[subtree]);
cout << n[root].getH();
}
catch (char c) { cout << c;} // tree attachment violation
}
return 0;
} |
|