-
Notifications
You must be signed in to change notification settings - Fork 5
/
r4.cpp
103 lines (87 loc) · 1.72 KB
/
r4.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// C++ program for the above approach
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
// Defining tree node
struct node {
int value;
struct node *right, *left;
};
// Utility function to create
// a new node
struct node* newnode(int key)
{
struct node* temp = new node;
temp->value = key;
temp->right = NULL;
temp->left = NULL;
return temp;
}
// Function to check binary
// tree whether its every node
// has value K or, it is
// connected with node having
// value K
bool connectedK(node* root,
node* parent,
int K,
bool flag)
{
// checking node value
if (root->value != K) {
// checking the left
// child value
if (root->left == NULL
|| root->left->value != K) {
// checking the rigth
// child value
if (root->right == NULL
|| root->right->value != K) {
// checking the parent value
if (parent == NULL
|| parent->value != K) {
flag = false;
return flag;
}
}
}
}
// Traversing to the left subtree
if (root->left != NULL) {
if (flag == true) {
flag
= connectedK(root->left,
root, K, flag);
}
}
// Traversing to the right subtree
if (root->right != NULL) {
if (flag == true) {
flag
= connectedK(root->right,
root, K, flag);
}
}
return flag;
}
// Driver code
int main()
{
// Input Binary tree
struct node* root = newnode(0);
root->right = newnode(1);
root->right->right = newnode(0);
root->left = newnode(0);
int K = 0;
// Function call to check
// binary tree
bool result
= connectedK(root, NULL,
K, true);
if (result == false)
cout << "False\n";
else
cout << "True\n";
return 0;
}