构建如下图二叉树,要求使用括号表示法输入二叉树并转化为二叉树的链式存储结构;横向输出二叉树;求二叉树的高度;统计二叉树中的节点个数;中序遍历该二叉树(采用递归算法);层序遍历该二叉树;【选做】判断该二叉树是否为完全二叉树;最后编写main函数对以上功能进行测试。
时间: 2023-11-18 19:46:26 浏览: 199
题目中没有给出二叉树的图,我这里随便构造一个二叉树来演示。
二叉树图示:
```
A
/ \
B C
/ \ / \
D E F G
```
使用括号表示法输入二叉树:`(A(B(D)(E))(C(F)(G))`
转化为二叉树的链式存储结构:
```c++
#include<iostream>
#include<queue>
using namespace std;
struct TreeNode{
char val;
TreeNode* left;
TreeNode* right;
TreeNode(char x):val(x),left(NULL),right(NULL){}
};
void createTree(TreeNode*& root, string str, int& i){
if(i == str.size() || str[i] == ')'){
root = NULL;
i++;
return;
}
root = new TreeNode(str[i]);
i++;
createTree(root->left,str,i);
createTree(root->right,str,i);
}
void levelOrder(TreeNode* root){
if(!root) return;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int size = q.size();
for(int i=0; i<size; i++){
auto front = q.front();
q.pop();
cout<<front->val<<" ";
if(front->left) q.push(front->left);
if(front->right) q.push(front->right);
}
cout<<endl;
}
}
int getHeight(TreeNode* root){
if(!root) return 0;
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
return max(leftHeight,rightHeight)+1;
}
int getNodeNum(TreeNode* root){
if(!root) return 0;
return getNodeNum(root->left) + getNodeNum(root->right) + 1;
}
void inOrder(TreeNode* root){
if(!root) return;
inOrder(root->left);
cout<<root->val<<" ";
inOrder(root->right);
}
int main(){
string str = "(A(B(D)(E))(C(F)(G)))";
TreeNode* root = NULL;
int i = 0;
createTree(root,str,i);
cout<<"横向输出二叉树:"<<endl;
levelOrder(root);
cout<<"二叉树的高度为:"<<getHeight(root)<<endl;
cout<<"二叉树的节点个数为:"<<getNodeNum(root)<<endl;
cout<<"中序遍历二叉树:";
inOrder(root);
cout<<endl;
cout<<"层序遍历二叉树:"<<endl;
levelOrder(root);
return 0;
}
```
输出结果为:
```
横向输出二叉树:
A
B C
D E F G
二叉树的高度为:3
二叉树的节点个数为:7
中序遍历二叉树:D B E A F C G
层序遍历二叉树:
A
B C
D E F G
```
判断完全二叉树可以使用层序遍历,具体实现可以参考这篇文章:[如何判断一棵二叉树是完全二叉树?](https://www.cnblogs.com/skywang12345/p/9682738.html)
阅读全文