c++设计算法求二叉树的结点个数,深度,并按前序次序打印二叉树中的叶子结点,并求树中结点x的第i个孩子
时间: 2024-05-01 20:19:11 浏览: 53
以下是C++的实现:
```C++
#include<iostream>
using namespace std;
// 树节点的结构
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 获取二叉树的结点个数
int getNodeNum(TreeNode* root) {
if (root == NULL) {
return 0;
}
return 1 + getNodeNum(root->left) + getNodeNum(root->right);
}
// 获取二叉树的深度
int getDepth(TreeNode* root) {
if (root == NULL) {
return 0;
}
int left_depth = getDepth(root->left);
int right_depth = getDepth(root->right);
return max(left_depth, right_depth) + 1;
}
// 按前序次序打印二叉树中的叶子结点
void printLeafNodes(TreeNode* root) {
if (root == NULL) {
return;
}
if (root->left == NULL && root->right == NULL) {
cout << root->val << " ";
}
printLeafNodes(root->left);
printLeafNodes(root->right);
}
// 获取树中结点x的第i个孩子
TreeNode* getIthChild(TreeNode* root, int x, int i) {
if (root == NULL) {
return NULL;
}
if (root->val == x) {
if (i == 1) {
return root->left;
} else if (i == 2) {
return root->right;
} else {
return NULL;
}
}
TreeNode* child = getIthChild(root->left, x, i);
if (child != NULL) {
return child;
}
return getIthChild(root->right, x, i);
}
int main() {
// 构建一个二叉树
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
// 获取二叉树的结点个数和深度
cout << "Node num: " << getNodeNum(root) << endl;
cout << "Depth: " << getDepth(root) << endl;
// 按前序次序打印二叉树中的叶子结点
cout << "Leaf nodes: ";
printLeafNodes(root);
cout << endl;
// 获取结点2的第1个孩子
TreeNode* child = getIthChild(root, 2, 1);
if (child != NULL) {
cout << "Node 2, child 1: " << child->val << endl;
} else {
cout << "Node 2, child 1 not found" << endl;
}
return 0;
}
```
输出结果为:
```
Node num: 7
Depth: 3
Leaf nodes: 4 5 6 7
Node 2, child 1: 4
```
阅读全文