-
Notifications
You must be signed in to change notification settings - Fork 0
/
bttransversal.cpp
72 lines (61 loc) · 1.51 KB
/
bttransversal.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
using namespace std;
// Data structure to store a Binary Tree node
struct Node
{
int key;
Node *left, *right;
Node(int key)
{
this->key = key;
this->left = this->right = nullptr;
}
};
// Function to print all nodes of a given level from left to right
bool printLevel(Node* root, int level)
{
if (root == nullptr)
return false;
if (level == 1)
{
cout << root->key << " ";
// return true if at-least one node is present at given level
return true;
}
bool left = printLevel(root->left, level - 1);
bool right = printLevel(root->right, level - 1);
//until both left and right are empty
return left || right;
}
// Function to print level order traversal of given binary tree
void levelOrderTraversal(Node* root)
{
// start from level 1 -- till height of the tree
int level = 1;
// run till printLevel() returns false
while (printLevel(root, level))
level++;
}
void preOrderTraversal(Node* root){
if (root==NULL)
return;
cout<<root->key<<" ";
preOrderTraversal(root->left);
preOrderTraversal(root->right);
}
// main function
int main()
{
Node* root = nullptr;
root = new Node(15);
root->left = new Node(10);
root->right = new Node(20);
root->left->left = new Node(8);
root->left->right = new Node(12);
root->right->left = new Node(16);
root->right->right = new Node(25);
levelOrderTraversal(root);
cout<<"\n";
preOrderTraversal(root);
return 0;
}