1
+ #include < iostream>
2
+ #include < vector>
3
+ using namespace std ;
4
+
5
+ // Node class
6
+ class Node
7
+ {
8
+ public:
9
+ int data;
10
+ Node *left;
11
+ Node *right;
12
+
13
+ Node (int val)
14
+ {
15
+ data = val;
16
+ left = right = NULL ;
17
+ }
18
+ };
19
+
20
+ static int idx = -1 ;
21
+
22
+ // Build tree from preorder traversal
23
+ Node *buildTree (vector<int > preorder)
24
+ {
25
+ idx++;
26
+
27
+ // base case
28
+ if (preorder[idx] == -1 )
29
+ {
30
+ return NULL ;
31
+ }
32
+
33
+ // create root node
34
+ Node *root = new Node (preorder[idx]);
35
+
36
+ // left subtree
37
+ root->left = buildTree (preorder);
38
+
39
+ // right subtree
40
+ root->right = buildTree (preorder);
41
+
42
+ return root;
43
+ }
44
+
45
+ // Find a node with a given value
46
+ Node *findNode (Node *root, int val)
47
+ {
48
+ if (root == NULL )
49
+ return NULL ;
50
+
51
+ if (root->data == val)
52
+ return root;
53
+
54
+ Node *leftResult = findNode (root->left , val);
55
+ if (leftResult != NULL )
56
+ return leftResult;
57
+
58
+ return findNode (root->right , val);
59
+ }
60
+
61
+ // Lowest common ancestor function
62
+ Node *lowestCommonAncestor (Node *root, Node *p, Node *q)
63
+ {
64
+ if (root == NULL )
65
+ return NULL ;
66
+
67
+ if (root->data == p->data || root->data == q->data )
68
+ return root;
69
+
70
+ Node *leftLCA = lowestCommonAncestor (root->left , p, q);
71
+ Node *rightLCA = lowestCommonAncestor (root->right , p, q);
72
+
73
+ if (leftLCA && rightLCA)
74
+ return root;
75
+ else if (leftLCA != NULL )
76
+ return leftLCA;
77
+ else
78
+ return rightLCA;
79
+ }
80
+
81
+ int main ()
82
+ {
83
+ vector<int > preorder = {1 , 2 , 7 , -1 , -1 , -1 , 3 , 4 , -1 , -1 , 5 , -1 , -1 };
84
+ Node *root = buildTree (preorder);
85
+
86
+ // Find two nodes
87
+ Node *p = findNode (root, 4 );
88
+ Node *q = findNode (root, 5 );
89
+
90
+ // Find and print LCA
91
+ Node *lca = lowestCommonAncestor (root, p, q);
92
+ if (lca != NULL )
93
+ cout << " Lowest Common Ancestor: " << lca->data << endl;
94
+ else
95
+ cout << " Lowest Common Ancestor not found." << endl;
96
+
97
+ return 0 ;
98
+ }
0 commit comments