题目:
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______3______ / ___5__ ___1__ / \ / 6 _2 0 8 / 7 4
For example, the lowest common ancestor (LCA) of nodes 5
and 1
is 3
. Another example is LCA of nodes 5
and 4
is 5
, since a node can be a descendant of itself according to the LCA definition.
链接: http://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
题解:
普通二叉树求公共祖先。看过<剑指Offer>以后知道这道题应该形成一系列问题。比如是不是二叉树,是不是BST。假如是BST的话我们可以用上题的方法,二分搜索。有没有指向父节点的link,假如有指向父节点的link我们就可以用intersection of two lists的方法找到两个linked list相交的地方。 对这道题目,我们使用后续遍历来做:
Time Complexity - O(n), Space Complexity - O(n)
public class Solution { public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null) return null; if (root == p || root == q) return root; TreeNode left = lowestCommonAncestor(root.left, p, q); // Post order traveral TreeNode right = lowestCommonAncestor(root.right, p, q); if (left != null && right != null) // p and q in two subtrees return root; else return left != null ? left : right; } }
Reference:
236. Lowest Common Ancestor of a Binary Tree
原文:http://www.cnblogs.com/yrbbest/p/5003803.html