Created
November 8, 2014 17:50
-
-
Save wszdwp/5e6560fd32cd728be064 to your computer and use it in GitHub Desktop.
LCA - Lowest common ancestor in a binary tree
This file contains hidden or 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
| //http://leetcode.com/2011/07/lowest-common-ancestor-of-a-binary-tree-part-i.html | |
| public class LCA | |
| { | |
| public static TreeNode findTheLowestCommonAncestor(TreeNode root, TreeNode nd1, TreeNode nd2) { | |
| if (root == null) | |
| return null; | |
| if (root == nd1 || root == nd2) | |
| return root; | |
| TreeNode left = findTheLowestCommonAncestor(root.left, nd1, nd2); | |
| TreeNode right = findTheLowestCommonAncestor(root.right, nd1, nd2); | |
| if (left != null && right != null) | |
| return root; | |
| else | |
| return left == null ? right : left; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment