-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathNth-node_of_inorder_traversal.cpp
More file actions
63 lines (51 loc) · 1.19 KB
/
Nth-node_of_inorder_traversal.cpp
File metadata and controls
63 lines (51 loc) · 1.19 KB
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
// C program for nth nodes of inorder traversals
#include <stdio.h>
#include <stdlib.h>
/* 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)
printf("%d ", node->data);
/* 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;
}
//Time Complexity: O(n)