LeetCode – Lowest Common Ancestor of a Binary Tree (Java)
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
Java Solution 1
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root==null) return null; if(root==p || root==q) return root; TreeNode l = lowestCommonAncestor(root.left, p, q); TreeNode r = lowestCommonAncestor(root.right, p, q); if(l!=null&&r!=null){ return root; }else if(l==null&&r==null){ return null; }else{ return l==null?r:l; } } |
To calculate time complexity, we know that f(n)=2*f(n-1)=2*2*f(n-2)=2^(logn), so time=O(n).
Java Solution 2
class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { CounterNode n = helper(root, p, q); return n.node; } public CounterNode helper(TreeNode root, TreeNode p, TreeNode q){ if(root==null){ return new CounterNode(null, 0); } CounterNode left = helper(root.left, p, q); if(left.count==2){ return left; } CounterNode right = helper(root.right, p, q); if(right.count==2){ return right; } int c=left.count+right.count+(root==p?1:0)+(root==q?1:0); return new CounterNode(root, c); } } class CounterNode{ public int count; public TreeNode node; public CounterNode(TreeNode node, int count){ this.count=count; this.node=node; } } |
<pre><code> String foo = "bar"; </code></pre>
-
Kishore Srinivas
-
Rajesh
-
Cesar Gonzalez
-
Birendra Singh
-
Titan
-
nidhi pitroda
-
Hooman
-
Cherry Zhao
-
Ameya Naik
-
w4nderlust
-
ryanlr
-
Ankit Shah
-
Sirius