二叉树的创建与遍历 (附C++代码)
程序员文章站
2022-05-20 14:05:38
...
二叉树的创建
创建二叉树节点
class Node {
public:
float data; // 节点数据
Node * leftChiled = nullptr; // 左孩子
Node * rightChiled = nullptr; // 右孩子
Node(float data) // 构造函数
:data(data)
{}
};
先序遍历
void preOrder(Node & node) {
cout << node.data << " ";
if(node.leftChiled != nullptr) {
preOrder(*(node.leftChiled));
}
if(node.rightChiled != nullptr) {
preOrder(*(node.rightChiled));
}
}
中序遍历
void midOrder(Node & node) {
if(node.leftChiled != nullptr) {
midOrder(*(node.leftChiled));
}
cout << node.data << " ";
if(node.rightChiled != nullptr) {
midOrder(*(node.rightChiled));
}
}
后序遍历
void postOrder(Node & node) {
if(node.leftChiled != nullptr) {
postOrder(*(node.leftChiled));
}
if(node.rightChiled != nullptr) {
postOrder(*(node.rightChiled));
}
cout << node.data << " ";
}
主函数
int main() {
//所生成的二叉树
/*
* 6(root)
* 5(one) 7(two)
* 0(three) 2(four) 9(five)
*/
//创建二叉树的根及若干节点
Node root(6);
Node one(5);
Node two(7);
Node three(0);
Node four(2);
Node five(9);
//拼接节点
root.leftChiled = &one;
root.rightChiled = &two;
one.leftChiled = &three;
one.rightChiled = &four;
two.rightChiled = &five;
//先序遍历
cout << "先序遍历结果:" << endl;
preOrder(root);
cout << endl;
cout << endl;
//中序遍历
cout << "中序遍历结果:" << endl;
midOrder(root);
cout << endl;
cout << endl;
//后序遍历
cout << "后序遍历结果:" << endl;
postOrder(root);
cout << endl;
cout << endl;
}
输出:
先序遍历结果:
6 5 0 2 7 9
中序遍历结果:
0 5 2 6 7 9
后序遍历结果:
0 2 5 9 7 6
上一篇: 126. 单词接龙 II
下一篇: SpringBoot执行流程