Recursive traversal is relatively simple ~
Preorder traversal-recursion
void preOrderTraversal(TreeNode* root){
if(root == nullptr){
return;
}
visit(root);
preOrderTraversal(root->left);
preOrderTraversal(root->right);
}
Preorder-non-recursive traversal-with the help of the stack
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
vector<int> preOrderTraversal(TreeNode* root){
vector<int> result;
if(root == nullptr){
return result;
}
stack<TreeNode*> s;
s.push(root);
while(!s.empty()){
TreeNode* currentNode = s.pop();
result.push_back(currentNode->value);
if(currentNode->right){
s.push(currentNode->right);
}
if(currentNode->left){
s.push(currentNode->left);
}
s.pop();
}
return result;
}
In-order traversal-recursion
void inOrderTraversal(TreeNode* root){
if(root == nullptr){
return;
}
inOrderTraversal(root->left);
visit(root);
inOrderTraversal(root->right);
}
Mid-order-non-recursive traversal-with the help of the stack
#include <iostream>
#include <stack>
using namespace std;
vector<int> inOrderTraversal(TreeNode* root){
vector<int> result;
if(root == nullptr){
return result;
}
stack<TreeNode*> s;
TreeNode* currentNode = root;
while(currentNode != nullptr){
while(currentNode != nullptr){
s.push(currentNode);
currentNode = currentNode->left;
}
if(!s.empty()){
currentNode = s.top();
result.push_back(currentNode->value);
currentNode = currentNode->right;
}
}
return result;
}
Postorder traversal-recursive
void postOrderTraversal(TreeNode* root){
if(root == nullptr){
return;
}
postOrderTraversal(root->left);
postOrderTraversal(root->right);
visit(root);
}
Post-order traversal-non-recursive implementation
Sequence traversal-recursion
Sequence traversal-non-recursive implementation
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<int> levelOrderTraversal(TreeNode* root){
vector<int> result;
if(root == nullptr){
return result;
}
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
TreeNode* currentNode = q.front();
result.push(currentNode->value);
if(currentNode->left != nullptr){
result.push(currentNode->left);
}
if(currentNode->left != nullptr){
result.push(currentNode->right);
}
q.pop();
}
return result;
}