-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathFind_nth_node_of_inorder_traversal.cpp
60 lines (49 loc) · 1.26 KB
/
Find_nth_node_of_inorder_traversal.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
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node {
int data;
struct Node* left;
struct Node* right;
};
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct Node* newNode(int data)
{
struct Node* node
= (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
/* Given a binary tree, print its nth nodes of inorder*/
void NthInorder(struct Node* node, int n)
{
static int count = 0;
if (node == NULL)
return;
if (count <= n) {
/* first recur on left child */
NthInorder(node->left, n);
count++;
// when count = n then print element
if (count == n)
cout << node->data<< endl;
/* now recur on right child */
NthInorder(node->right, n);
}
}
/* Driver program to test above functions*/
int main()
{
struct Node* root = newNode(10);
root->left = newNode(20);
root->right = newNode(30);
root->left->left = newNode(40);
root->left->right = newNode(50);
int n = 4;
NthInorder(root, n);
return 0;
}