leetcode 236Lowest Common Ancestor of a Binary Tree [python]
来源:互联网 发布:四个字的网络用语 编辑:程序博客网 时间:2024/05/21 07:08
- I.题目简述
- II.思路及实现
- III.总结归纳
I.题目简述
给定一课二叉树,求两个树的最低公共祖先
[2,5]的最低公共祖先为5
[2,8]的最低公共祖先为3
II.思路及实现
思路:①递归判断树的左右子树是否为这两个节点公共祖先(自顶向下递归方法)
②为实现方法①需写相关某一个结点是否为该节点祖先的方法
扩展:这里类似对于判断二叉树是否为平衡二叉树的思路类似(需要实现求树的深度方法)
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ if not root or p==root or q==root: return root if self.isnode(p,q): return p if self.isnode(p,q): return q if self.isnode(root.left,p) and self.isnode(root.left,q): return self.lowestCommonAncestor(root.left,p,q) if self.isnode(root.right,p) and self.isnode(root.right,q): return self.lowestCommonAncestor(root.right,p,q) else: return root def isnode(self,mother,child): if mother: if mother==child: return True else: return self.isnode(mother.left,child) or self.isnode(mother.right,child) return False
III.总结归纳
①关于树这类的题目在遍历的方法实现以及树的基本概念的结合是解决此类的问题的基础,大家需要熟悉②让我们一同努力,明天会更好!
0 0
- leetcode 236Lowest Common Ancestor of a Binary Tree [python]
- 【LeetCode】236 Lowest Common Ancestor of a Binary Tree
- leetcode 236: Lowest Common Ancestor of a Binary Tree
- Leetcode 236 Lowest Common Ancestor of a Binary Tree
- LeetCode 236 Lowest Common Ancestor of a Binary Tree
- [Leetcode 236, Medium] Lowest Common Ancestor of a Binary Tree
- leetcode[236]:Lowest Common Ancestor of a Binary Tree
- Leetcode NO.236 Lowest Common Ancestor of a Binary Tree
- Leetcode #236 Lowest Common Ancestor of a Binary Tree
- [leetcode 236]Lowest Common Ancestor of a Binary Tree
- LeetCode 236 Lowest Common Ancestor of a Binary Tree
- [LeetCode 236] Lowest Common Ancestor of a Binary Tree
- LeetCode(236)Lowest Common Ancestor of a Binary Tree
- leetcode 236: Lowest Common Ancestor of a Binary Tree
- LeetCode 236: Lowest Common Ancestor of a Binary Tree
- 【LEETCODE】236-Lowest Common Ancestor of a Binary Tree
- LeetCode 236 Lowest Common Ancestor of a Binary Tree
- 【LeetCode-236】Lowest Common Ancestor of a Binary Tree
- zabbix[2]-自动注册
- Intent 使用Action 和Data 属性启动系统activity
- eclipse插件运行时获取文件路径
- js 截取url中的多个参数
- android颜色对应的xml配置值,颜色表
- leetcode 236Lowest Common Ancestor of a Binary Tree [python]
- oracle日期格式转换 to_date(),to_char()
- JSON
- 听过中文编程语言吗?来来来!
- 终于搞懂了CSS实现三角形图标的原理
- Dubbo 简单实例
- recylview和listview中item如何设置点击效果?
- 聊一聊Android 6.0的运行时权限
- 互联网协议入门