c++ 二叉树 前序中序后序遍历二叉树 计算树的深度 计算叶子结点个数 查找双亲 查找兄弟 代码
时间: 2024-02-25 08:59:04 浏览: 77
二叉树的定义:
```c++
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
```
前序遍历:
```c++
void preOrder(TreeNode* root) {
if (root == nullptr) return;
cout << root->val << " ";
preOrder(root->left);
preOrder(root->right);
}
```
中序遍历:
```c++
void inOrder(TreeNode* root) {
if (root == nullptr) return;
inOrder(root->left);
cout << root->val << " ";
inOrder(root->right);
}
```
后序遍历:
```c++
void postOrder(TreeNode* root) {
if (root == nullptr) return;
postOrder(root->left);
postOrder(root->right);
cout << root->val << " ";
}
```
计算树的深度:
```c++
int depth(TreeNode* root) {
if (root == nullptr) return 0;
int leftDepth = depth(root->left);
int rightDepth = depth(root->right);
return max(leftDepth, rightDepth) + 1;
}
```
计算叶子节点个数:
```c++
int countLeafNodes(TreeNode* root) {
if (root == nullptr) return 0;
if (root->left == nullptr && root->right == nullptr) return 1;
return countLeafNodes(root->left) + countLeafNodes(root->right);
}
```
查找双亲节点:
```c++
TreeNode* getParent(TreeNode* root, TreeNode* child) {
if (root == nullptr || root == child) return nullptr;
if (root->left == child || root->right == child) return root;
TreeNode* parent = getParent(root->left, child);
if (parent != nullptr) return parent;
return getParent(root->right, child);
}
```
查找兄弟节点:
```c++
TreeNode* getSibling(TreeNode* root, TreeNode* child) {
if (root == nullptr || root == child) return nullptr;
if (root->left == child) return root->right;
if (root->right == child) return root->left;
TreeNode* sibling = getSibling(root->left, child);
if (sibling != nullptr) return sibling;
return getSibling(root->right, child);
}
```
注意:以上代码仅供参考,实际使用中需要根据具体情况进行修改和适配。
阅读全文