[勇者闯LeetCode] 110. Balanced Binary Tree
来源:互联网 发布:数据挖掘 面试 编辑:程序博客网 时间:2024/05/16 17:56
[勇者闯LeetCode] 110. Balanced Binary Tree
Description
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Information
- Tags: Tree | Depth-first Search
- Difficulty: Easy
Solution
利用DFS得到每个节点的高度,若节点的两个子树不平衡,则该节点的高度设为-1,最后通过二叉树的高度是否大于等于0来决定二叉树是否平衡。
Python Code
# 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.get_height(root) >= 0) def get_height(self, root): if root is None: return 0 left_h, right_h = self.get_height(root.left), self.get_height(root.right) if left_h < 0 or right_h < 0 or abs(left_h - right_h) > 1: return -1 return max(left_h, right_h) + 1;
0 0
- [勇者闯LeetCode] 110. Balanced Binary Tree
- [勇者闯LeetCode] 257. Binary Tree Paths
- [勇者闯LeetCode] 104. Maximum Depth of Binary Tree
- [勇者闯LeetCode] 107. Binary Tree Level Order Traversal II
- [勇者闯LeetCode] 111. Minimum Depth of Binary Tree
- [勇者闯LeetCode] 100. Same Tree
- [勇者闯LeetCode] 101. Symmetric Tree
- [勇者闯LeetCode] 108. Convert Sorted Array to Binary Search Tree
- LeetCode 110. Balanced Binary Tree
- [LeetCode]110.Balanced Binary Tree
- 【LeetCode】110.Balanced Binary Tree
- [Leetcode] 110. Balanced Binary Tree
- LeetCode --- 110. Balanced Binary Tree
- [leetcode] 110.Balanced Binary Tree
- [leetcode]110. Balanced Binary Tree
- LeetCode:110. Balanced Binary Tree
- 110. Balanced Binary Tree LeetCode
- [LeetCode]110. Balanced Binary Tree
- java基础总结15-面向对象11(抽象类)
- 在线黑科技小工具
- MySQL实验(三) 过程式数据库对象的使用
- java.util.Date和java.sql.Date的区别和相互转化
- 百练_3671字符串排序
- [勇者闯LeetCode] 110. Balanced Binary Tree
- NYPJ 蛇形填数
- 腾讯面经:错过校招的我如何在社招进入鹅厂
- 学习MVC之租房网站(五)-权限、角色、用户管理
- 绘制人物属性的六芒星
- 水晶报表中让行高自适应高度(即根据内容的来适应高度)
- Rmi远程调用机制
- Java设计模式《七》模板方法模式
- Linux下which、whereis、locate、find 命令的区别