标签:Lowest Binary TreeNode 二叉树 LCA return nodes null root
题目
给定二叉树和两个点,求两点的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本身 } }
标签:Lowest,Binary,TreeNode,二叉树,LCA,return,nodes,null,root 来源: https://www.cnblogs.com/inku/p/15640869.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。