Created
June 12, 2017 15:49
-
-
Save InterviewBytes/75e6c581b1a5bdf6f6f26e3e0462fd64 to your computer and use it in GitHub Desktop.
LCA Binary Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.interviewbytes.trees; | |
public class LowestCommonAncestorBinaryTree { | |
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { | |
if (root == null || root == p || root == q) return root; | |
TreeNode left = lowestCommonAncestor(root.left, p, q); | |
TreeNode right = lowestCommonAncestor(root.right, p, q); | |
if (left != null && right != null) return root; | |
if (left == null) return right; | |
return left; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.interviewbytes.trees; | |
public class TreeNode { | |
int val; | |
TreeNode left; | |
TreeNode right; | |
TreeNode(int x) { | |
val = x; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment