Recursive function for the solution
| 17 | |
| 18 | // Recursive function for the solution |
| 19 | TreeNode* solve(TreeNode* root, int B, int C) { |
| 20 | |
| 21 | if(!root) return NULL; //Base condition - if we reach the leaves |
| 22 | |
| 23 | if(root->val==B || root->val==C) { //Base Condition - if any of the two given nodes is found then return that node |
| 24 | return root; |
| 25 | } |
| 26 | |
| 27 | TreeNode* left = solve(root->left,B,C); // Recusrive call for left tree |
| 28 | TreeNode* right = solve(root->right,B,C); // Recusive call for right tree |
| 29 | |
| 30 | if(left && right) { // If we have found both the given nodes then the current node is the LCA so return the current node |
| 31 | return root; |
| 32 | } |
| 33 | else return (left)?left:right; // else return one of the two nodes which is not null |
| 34 | } |
| 35 | |
| 36 | |
| 37 | int Solution::lca(TreeNode* A, int B, int C) { |