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 p
and q
as the lowest node in T
that has both p
and q
as descendants (where we allow a node to be a descendant of itself).”
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Output: 3 Explanation: The LCA of nodes 5 and 1 is 3.
Example 2:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 Output: 5 Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
Example 3:
Input: root = [1,2], p = 1, q = 2 Output: 1
Constraints:
- The number of nodes in the tree is in the range
[2, 105]
. -109 <= Node.val <= 109
- All
Node.val
are unique. p != q
p
andq
will exist in the tree.
二叉树的最近公共祖先。
题目跟235题很接近,唯一的不同是235题是一个二叉搜索树(BST),本题是一个二叉树。235题可以用递归做,但是本题比较难,需要用到后序遍历(postorder),因为无法用BST的性质判断p和q到底是在左子树还是在右子树。注意需要判断一个corner case,如果根节点为空,或者p和q里面有任何一个节点的 val 和根节点的 val 一样的情况,此时需要返回 root。
时间O(n)
空间O(h) - 树的高度
Java实现
1 class Solution { 2 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 3 if (root == null || root == p || root == q) return root; 4 TreeNode left = lowestCommonAncestor(root.left, p, q); 5 TreeNode right = lowestCommonAncestor(root.right, p, q); 6 if (left != null && right != null) { 7 return root; 8 } 9 return left == null ? right : left; 10 } 11 }
JavaScript实现
1 /** 2 * @param {TreeNode} root 3 * @param {TreeNode} p 4 * @param {TreeNode} q 5 * @return {TreeNode} 6 */ 7 var lowestCommonAncestor = function (root, p, q) { 8 if (root == null || root == p || root == q) return root; 9 let left = lowestCommonAncestor(root.left, p, q); 10 let right = lowestCommonAncestor(root.right, p, q); 11 if (left !== null && right !== null) { 12 return root; 13 } 14 return left == null ? right : left; 15 };
根据代码,跑一下example 1,p = 5,q = 1。因为是后序遍历所以先从叶子节点开始找,节点7和节点4满足11行(JS)所以会return他们本身;再往上找的时候会找到他们的父节点2,再找到6和2的父节点5。此时5和1满足11行,所以会return根节点3。
相关题目
235. Lowest Common Ancestor of a Binary Search Tree
236. Lowest Common Ancestor of a Binary Tree