[leetcode] 68.二叉树的最近公共祖先
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                [leetcode] 68.二叉树的最近公共祖先
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                給定一個二叉樹, 找到該樹中兩個指定節點的最近公共祖先。
百度百科中最近公共祖先的定義為:“對于有根樹 T 的兩個節點 p、q,最近公共祖先表示為一個節點 x,滿足 x 是 p、q 的祖先且 x 的深度盡可能大(一個節點也可以是它自己的祖先)。”
示例 1:
?
輸入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
 輸出:3
 解釋:節點 5 和節點 1 的最近公共祖先是節點 3 。
示例 2:
?
輸入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
 輸出:5
 解釋:節點 5 和節點 4 的最近公共祖先是節點 5 。因為根據定義最近公共祖先節點可以為節點本身。
示例 3:
輸入:root = [1,2], p = 1, q = 2 輸出:1 class Solution:def lowestCommonAncestor(self,root:'TreeNode',p:'TreeNode',q:'TreeNode')->'TreeNode':if not root or root == p or root == q:return rootleft = self.lowestCommonAncestor(root.left)right = self.lowestCommonAncestor(root.right)if not left and not right:return Noneelif left and not right:return leftelif right and not left:return rightreturn root總結
以上是生活随笔為你收集整理的[leetcode] 68.二叉树的最近公共祖先的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: [leetcode] 230.二叉搜索树
- 下一篇: [leetcode]509. 斐波那契数
