Advertisement
jayati

Lowest Common Ancestor of a Binary Tree

May 14th, 2024
410
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.76 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8.  * };
  9.  */
  10. class Solution {
  11. public:
  12.     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  13.  
  14.         if(root==NULL || root==p || root==q)
  15.         {
  16.             return root;
  17.         }
  18.  
  19.         TreeNode* left = lowestCommonAncestor(root->left,p,q);
  20.         TreeNode* right = lowestCommonAncestor(root->right,p,q);
  21.  
  22.         if(left==NULL)
  23.         {
  24.             return right;
  25.         }
  26.         else if(right==NULL)
  27.         {
  28.             return left;
  29.         }
  30.         else
  31.         {
  32.             return root;
  33.         }
  34.        
  35.     }
  36. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement