[Leetcode 235/236]LCA二叉树最近公共祖先Lowest Common Ancestor of a Binary Tree
2021/12/4 6:16:45
本文主要是介绍[Leetcode 235/236]LCA二叉树最近公共祖先Lowest Common Ancestor of a Binary Tree,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
题目
给定二叉树和两个点,求两点的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本身 } }
这篇关于[Leetcode 235/236]LCA二叉树最近公共祖先Lowest Common Ancestor of a Binary Tree的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23增量更新怎么做?-icode9专业技术文章分享
- 2024-11-23压缩包加密方案有哪些?-icode9专业技术文章分享
- 2024-11-23用shell怎么写一个开机时自动同步远程仓库的代码?-icode9专业技术文章分享
- 2024-11-23webman可以同步自己的仓库吗?-icode9专业技术文章分享
- 2024-11-23在 Webman 中怎么判断是否有某命令进程正在运行?-icode9专业技术文章分享
- 2024-11-23如何重置new Swiper?-icode9专业技术文章分享
- 2024-11-23oss直传有什么好处?-icode9专业技术文章分享
- 2024-11-23如何将oss直传封装成一个组件在其他页面调用时都可以使用?-icode9专业技术文章分享
- 2024-11-23怎么使用laravel 11在代码里获取路由列表?-icode9专业技术文章分享
- 2024-11-22怎么实现ansible playbook 备份代码中命名包含时间戳功能?-icode9专业技术文章分享