題目:
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相交的地方。 對這道題目,我們使用后續遍歷來做:
- 定義兩個輔助節點,使用后續遍歷來遍歷整個樹
- 當root的值等於p或者q時,找到一個符合條件的節點,返回這個root
- 先遍歷左子樹
- 再遍歷右子樹
- 當left,right均找到時返回此root
- 只找到left時返回left
- 只找到right時返回right
- 否則返回null
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; } }
二刷:
Java:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { 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; else return left != null ? left : right; } }
三刷
還是跟以前一樣的方法,利用遞歸,先遍歷兩個子樹,來查找是否其中含有目標節點p或者q。假如兩節點分別位於root的左右兩側,則root為LCA. 否則,left和right哪個非空,則哪一個為LCA, 這一側含有p和q兩個目標節點。
Java:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public 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); TreeNode right = lowestCommonAncestor(root.right, p, q); if (left != null && right != null) return root; else return (left != null) ? left : right; } }
Reference: