题目
给定二叉树和两个点,求两点的LCA最近公共祖先
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
思路
是一道套路题,A B俩点的位置只有三种情况
- A B 都在root左边(这时LCA必也在左边)
- A B 都在root右边(这时LCA必也在右边)
- A B 分别在root的左右边(这时LCA必为root)
代码
写起来很简单,但没想通为什么回溯之后得到的就是LCA,怎么证明
class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root==p||root==q||root==null) return root; TreeNode leftRoot=lowestCommonAncestor(root.left,p,q); TreeNode rightRoot=lowestCommonAncestor(root.right,p,q); if (leftRoot==null) return rightRoot;//root的left没有pq,即pq都在右边,LCA也在右边 else if(rightRoot==null) return leftRoot;//root的right没有pq,即pq都在左边,LCA也在左 else return root;//俩节点分别在root的左右俩边,那LCA就是rott本身 } }