二叉树的建立与遍历(先中后层序)
生活随笔
收集整理的這篇文章主要介紹了
二叉树的建立与遍历(先中后层序)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在做一些算法題時(shí),我會(huì)經(jīng)常用到VS2017去測試,每次去找一個(gè)合適的二叉樹覺得很麻煩,今天就自己寫了一個(gè)放在博客上,下次就直接復(fù)制了
包含二叉樹的建立,以及二叉樹的前序遍歷、中序遍歷、后序遍歷和層序遍歷
main.c
#include <iostream> #include <vector> #include <string> #include <queue> using namespace std;class Node { public:float data; // 節(jié)點(diǎn)數(shù)據(jù)Node * leftChiled = nullptr; // 左孩子Node * rightChiled = nullptr; // 右孩子Node(float data) :data(data) {}; 構(gòu)造函數(shù) };//先序遍歷 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 << " "; }//層序遍歷 vector<vector<int>> levelOrder(Node* root) {if (root == nullptr) return {};vector<vector<int>> ans;//利用q.size() 來保證當(dāng)前層的元素的數(shù)目queue<Node*> q;q.push(root);while (!q.empty()) {int qSize = q.size();ans.emplace_back(vector<int>());//先將ans插入一個(gè)空數(shù)組for (int i = 0; i < qSize; i++) {Node* temp = q.front();q.pop();ans.back().emplace_back(temp->data);//ans.back()就是剛才哪個(gè)空數(shù)組if (temp->leftChiled) q.push(temp->leftChiled);if (temp->rightChiled) q.push(temp->rightChiled);}}return ans; }int main() {//所生成的二叉樹/** 6(root)* 5(one) 7(two)* 0(three) 2(four) 9(five)*///創(chuàng)建二叉樹的根及若干節(jié)點(diǎn)Node root(6);Node one(5);Node two(7);Node three(0);Node four(2);Node five(9);//拼接節(jié)點(diǎn)root.leftChiled = &one;root.rightChiled = &two;one.leftChiled = &three;one.rightChiled = &four;two.rightChiled = &five;//先序遍歷cout << "先序遍歷結(jié)果:" << endl;preOrder(root);cout << endl;cout << endl;//中序遍歷cout << "中序遍歷結(jié)果:" << endl;midOrder(root);cout << endl;cout << endl;//后序遍歷cout << "后序遍歷結(jié)果:" << endl;postOrder(root);cout << endl;cout << endl;//層序遍歷cout << "層序遍歷結(jié)果:" << endl;vector<vector<int>> ans=levelOrder(&root);for(int i=0;i<ans.size();i++){for (auto data : ans[i])cout << data<<" ";cout << endl;}}結(jié)果顯示
總結(jié)
以上是生活随笔為你收集整理的二叉树的建立与遍历(先中后层序)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vs2017搭建Linux的开发调试环境
- 下一篇: 树莓派4B设置静态IP