LeetCode Balanced Binary Tree
来源:互联网 发布:java中的scanner 编辑:程序博客网 时间:2024/05/22 12:52
LeetCode解题之Balanced Binary Tree
原题
判断一棵二叉树是否是平衡二叉树,只有当每个节点的左右两棵子树的高度差不大于1时,这棵树才是平衡的。
注意点:
- 无
例子:
输入:
3 / \ 9 20 / \ 15 7 / 14
输出: False
解题思路
一个节点的高度是它左右两棵子树的高度较大值加一,为了使代码简练,定义不平衡的子树的高度为-1,所以在计算每个节点的高度时,要额外判断左右两棵子树是否平衡,如果不平衡(左子树不平衡 | 右子树不平衡 | 左右子树高度差大于1)就直接返回-1。
AC源码
# 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 isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ return self._isBalanced(root) >= 0 def _isBalanced(self, root): if not root: return 0 left, right = self._isBalanced(root.left), self._isBalanced(root.right) if left >= 0 and right >= 0 and abs(left - right) <= 1: return 1 + max(left, right) else: return -1if __name__ == "__main__": None
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
0 0
- LeetCode: Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [Leetcode] Balanced Binary Tree
- LeetCode : Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- 【leetcode】Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- [Leetcode]Balanced Binary Tree
- [leetcode]Balanced Binary Tree
- Leetcode: Balanced Binary Tree
- LeetCode-Balanced Binary Tree
- LeetCode - Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- LeetCode | Balanced Binary Tree
- 【leetcode】Balanced Binary Tree
- 使用Docker搭建hadoop集群
- 基于OpenWrt的PPTP插件适配Bootstrap
- 数据结构基础之图的存储结构
- linux 命令cp
- CodeForces 630 C. Lucky Numbers(水~)
- LeetCode Balanced Binary Tree
- 说明
- delegate、block和NSNotification传值
- 09 吃大便游戏的开发雏形-DirectX游戏开发初级教程
- Java构造器和方法的区别
- socket network programming
- java命令
- CodeForces 630 D. Hexagons!(水~)
- OC的类和对象