leetcode110~Balanced Binary Tree
来源:互联网 发布:node js ide 编辑:程序博客网 时间:2024/05/18 07:34
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.
判断一棵树是否为平衡二叉树。
平衡二叉树:对于树中每一个节点来说,左右子树的高度差不能超过1.
关键:使用递归求出子树高度,然后做差比较即可。返回-1代表非平衡。
在给出本题代码之前,先附上求树高度的代码,便于理解:
public int getHeight(TreeNode root){ if(root==null) return 0; int left = getHeight(root.left); int right = getHeight(root.right); return Math.max(left,right)+1;}
只需对上面代码稍微修改一下即可:
public class IsBalanced { public boolean isBalanced(TreeNode root) { if(getHeight(root)==-1) { return false; } else { return true; } } private int getHeight(TreeNode root) { if(root==null) return 0; int left = getHeight(root.left); int right = getHeight(root.right); if(left==-1 || right==-1 || Math.abs(left-right)>1) { return -1; } return Math.max(left, right)+1; }}
0 0
- LeetCode110 - Balanced Binary Tree
- LeetCode110-Balanced Binary Tree
- leetcode110---Balanced Binary Tree
- LeetCode110:Balanced Binary Tree
- LeetCode110. Balanced Binary Tree
- leetcode110~Balanced Binary Tree
- leetcode110. Balanced Binary Tree
- LeetCode110 Balanced Binary Tree
- leetcode110 Balanced Binary Tree
- Leetcode110. Balanced Binary Tree
- LeetCode110. Balanced Binary Tree
- LeetCode110—Balanced Binary Tree
- LeetCode110.Balanced Binary Tree题解
- LeetCode110——Balanced Binary Tree
- LeetCode110 Blanced Binary Tree Java 题解
- Balanced binary tree 扩展
- LeetCode: Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- Linux [root@bogon]怎么改成[root@yourname]
- 数据库连接池
- 统计IP个数
- 【Codeforces Round #398 (Div. 2)】Codeforces 767B The Queue
- Python 3 UnicodeEncodeError: 'gbk' codec can't encode错误的解决
- leetcode110~Balanced Binary Tree
- 【Mybatis】(二)Mybatis开发Dao对比学习
- 常见前端面试题及答案(下)
- Hibernate的HQL和Restrictions运算符
- Python中的GIL问题
- 行人检测论文笔记:Fast Feature Pyramids for Object Detection?
- 使用google注册教程
- 【机器学习实战-python3】决策树ID3
- 计算机的启动过程