Lowest Common Ancestor
236 LCA - given 2 nodes and root in Binary tree
Time O(n), space O(h)
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode node1, TreeNode node2) { // 碰到node1 or node2 就返回 if(root == null || root == node1 || root == node2){ return root; } TreeNode left = lowestCommonAncestor(root.left, node1, node2); TreeNode right = lowestCommonAncestor(root.right, node1, node2); if( left != null && right != null){ return root; } if(left != null){ return left; } if(right != null){ return right; } return null; }
LCA - given 2 nodes with parent pointer in same binary tree
Get depths of each nodes, make deeper node to the same level of another
Time O(h), Space O(1)
LCA - given 2 nodes with parent pointer, optimize for close ancestor
Use Hashtable
Time and Space O(D0 + D1)
235 LCA with BST
Worst case O(h)
Keep search the root in range [node0, node1]
1123. Lowest Common Ancestor of Deepest Leaves
Given a rooted binary tree, return the lowest common ancestor of its deepest leaves.
Last updated
Was this helpful?