#include <iostream>
#include <vector>
#include <stdio.h>
using namespace std;
class TreeNode {
public:
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
vector<int> res;
public:
void traverse(TreeNode* root,int level) {
if(root == nullptr) {
return ;
}
cout << "节点" << root->val << "在第" << level << "层" << endl;
traverse(root->left,level + 1);
traverse(root->right,level + 1);
}
int count(TreeNode* root) {
if(root == nullptr) {
return 0;
}
int leftCount = count(root->left);
int rightCount = count(root->right);
// printf("节点 %s 的左子树有 %d 个节点,右子树有 %d 个节点",root->val, leftCount, rightCount);
cout << "节点" << root->val << "的左子树有" << leftCount << "个节点,右子树有" << rightCount << "个节点" << endl;
return leftCount + rightCount + 1;
}
};
TreeNode* newNode(int data)
{
TreeNode* node = new TreeNode();
node->val = data;
node->left = NULL;
node->right = NULL;
return(node);
}
int main() {
/*creating tree*/
TreeNode *root = newNode(50);
root->left = newNode(30);
root->left->left = newNode(20);
root->left->right = newNode(40);
root->right = newNode(70);
root->right->left = newNode(60);
root->right->right = newNode(80);
// 50
// / \
// 30 70
// / \ / \
// 20 40 60 80
Solution solution;
solution.traverse(root,1);
int NodeCount = solution.count(root);
cout << "一共有" << NodeCount << "个节点" << endl;
return 0;
}