Find the lowest common ancestors in a binary tree.
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.
Approach
Java
public class LCABT {public static void main(String[] args) {TreeNode tree = new TreeNode(3);tree.left = new TreeNode(5);TreeNode p = tree.left;tree.right = new TreeNode(1);TreeNode q = tree.right;tree.left.left = new TreeNode(6);tree.left.right = new TreeNode(2);tree.right.left = new TreeNode(0);tree.right.right = new TreeNode(8);tree.left.right.left = new TreeNode(7);tree.left.right.right = new TreeNode(4);TreeNode incres = lowestCommonAncestor(tree, p, q);System.out.println(incres.val);}// function to find the lowest common// ancestor of the binary treeprivate static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {// base caseif (root == null)return null;// base case root data is same as// any one of p and then return rootif (root.val == p.val || root.val == q.val)return root;// find left LCATreeNode leftLCA = lowestCommonAncestor(root.left, p, q);// find right LCATreeNode rightLCA = lowestCommonAncestor(root.right, p, q);// if both are not NULL then return the rootif (leftLCA != null && rightLCA != null)return root;// if left is NULL return rightif (leftLCA == null)return rightLCA;// else return the leftreturn leftLCA;}}class TreeNode {int val;TreeNode left;TreeNode right;TreeNode() {}TreeNode(int val) {this.val = val;}TreeNode(int val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}}
C++
#include <bits/stdc++.h>using namespace std;//struct for treenodestruct TreeNode{int data;TreeNode *left;TreeNode *right;TreeNode(int data){this->data=data;this->left=NULL;this->right=NULL;}};//funtion to find the Lowest//common ancestor of binary treeTreeNode* lowestCommonAncestor(TreeNode* root,TreeNode* p, TreeNode* q){//base caseif(root==NULL)return NULL;//base case root data is same as//any one of p and then return rootif(root->data==p->data||root->data==q->data)return root;//find left LCATreeNode *leftLCA=lowestCommonAncestor(root->left,p,q);//find right LCATreeNode *rightLCA=lowestCommonAncestor(root->right,p,q);//if both are not NULL then return the rootif(leftLCA!=NULL&&rightLCA!=NULL)return root;//if left is NULL return rightif(leftLCA==NULL)return rightLCA;//else return the leftreturn leftLCA;}int main(){TreeNode *tree=new TreeNode(3);tree->left=new TreeNode(5);TreeNode *p=tree->left;tree->right=new TreeNode(1);TreeNode *q=tree->right;tree->left->left=new TreeNode(6);tree->left->right=new TreeNode(2);tree->right->left=new TreeNode(0);tree->right->right=new TreeNode(8);tree->left->right->left=new TreeNode(7);tree->left->right->right=new TreeNode(4);TreeNode *LCA=lowestCommonAncestor(tree,p,q);cout<<LCA->data<<"\n";return 0;}
No comments:
Post a Comment