有道题不太会,求助大佬们:
在二叉搜索树的基础上,计算每个节点的左子节树的节点数量和右子节点树的节点数量。 如何建立这样的二叉搜索树
我的错误代码(中序输出正确,左右节点数量不对):
#include<bits/stdc++.h>
using namespace std;
struct Node{
int key;
struct Node *left;
struct Node *right;
struct Node *parent;
int result;
int resultright;
int resultleft;
};
void makeNode(struct Node *n, int m){
if(n == 0){
return;
}
if(m < n->key){
if(n->left == 0){
struct Node *newNode = new struct Node();
newNode->key = m;
newNode->left = 0;
newNode->right = 0;
newNode->parent = n;
n->left = newNode;
newNode->resultleft++;
}
else{
makeNode(n->left, m);
}
}
if(m > n->key){
if(n->right == 0){
struct Node *newNode = new struct Node();
newNode->key = m;
newNode->left = 0;
newNode->right = 0;
newNode->parent = n;
n->right = newNode;
newNode->resultright++;
}
else{
makeNode(n->right, m);
}
}
}
void print(struct Node *n){
if(n == 0){
return;
}
print(n->left);
cout << n->key << " ";
print(n->right);
}
struct Node* search(struct Node *n, int t){
if(n == 0){
return 0;
}
if(t == n->key){
return n;
}
else if(t < n->key){
return search(n->left, t);
}
else{
return search(n->right, t);
}
}
int main(){
struct Node root;
cin >> root.key;
root.left = 0;
root.right = 0;
root.parent = 0;
for(int i = 0;i<7;i++){
int m;
cin >> m;
makeNode(&root, m);
}
print(&root);
struct Node* p = search(&root, 55);
if(p != 0){
cout << p->key << " ";
}
cout << root.resultright;
cout << root.resultleft;
return 0;
}
麻烦大佬们帮我看看
//在线等,急