二叉树前中后、层次遍历
生活随笔
收集整理的這篇文章主要介紹了
二叉树前中后、层次遍历
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
#include<iostream> #include<stack> #include<queue> using namespace std;/* 二叉樹遍歷算法遞歸+非遞歸: 前序遍歷:根->左->右 中序遍歷:左->根->右 后序遍歷:左->右->根 層次遍歷 */ struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x): val(x),left(NULL),right(NULL) {} };/*遞歸版本*/ void prerecusive(TreeNode *root) {if (!root) return;cout << root->val << " ";prerecusive(root->left);prerecusive(root->right); } void inrecusive(TreeNode *root) {if (!root) return;inrecusive(root->left);cout << root->val << " ";inrecusive(root->right); } void postrecusive(TreeNode *root) {if (!root) return;postrecusive(root->left);postrecusive(root->right);cout << root->val << " "; }/*循環版本。棧做輔助*/ void preiteration(TreeNode *root) {if (!root) return;stack<TreeNode *> s;s.push(root);while (!s.empty()){TreeNode *curr=s.top();cout << curr->val << " ";s.pop();if (curr->right) s.push(curr->right);if (curr->left) s.push(curr->left);} } void initeration(TreeNode *root) {if (!root) return;stack<TreeNode *> s;TreeNode *curr = root;while (curr || !s.empty())//s沒有值,第一個判斷條件是curr不是空 {if (curr){s.push(curr);curr = curr->left;}else{cout << s.top()->val << " ";curr = s.top()->right;s.pop();}} } void postiteration(TreeNode *root) {if (!root) return;stack<TreeNode *> s;s.push(root);TreeNode *curr;TreeNode *visited;//記錄子節點已經訪問過while (!s.empty()){curr = s.top();/** 出棧條件:* 對于葉子節點:直接彈出* 對于非葉子節點:如果已經遍歷過其左子節點或右子節點,則彈出*/if ((!curr->left && !curr->right) || (visited && (curr->left==visited || curr->right == visited))){cout << curr->val << " ";visited = curr;s.pop();}else{if (curr->right) s.push(curr->right);if (curr->left) s.push(curr->left);}} }void leveltraverse(TreeNode *root) {if (!root) return;queue<TreeNode *> q;TreeNode *curr;q.push(root);while (!q.empty()){curr = q.front();cout << curr->val << " ";q.pop();if (curr->left) q.push(curr->left);if (curr->right) q.push(curr->right);} }
?
轉載于:https://www.cnblogs.com/beixiaobei/p/10914253.html
總結
以上是生活随笔為你收集整理的二叉树前中后、层次遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Cloud与Duddo比较
- 下一篇: Mybatis逆向工程的pojo实现序列