leetcode -- 110. Balanced Binary Tree 【二叉树是否平衡】
2017-02-09 13:04
555 查看
题目
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.
分析及解答
【平衡因子】
某结点的左子树与右子树的高度(深度)差即为该结点的平衡因子(BF,Balance Factor)。
平衡二叉树上所有结点的平衡因子只可能是 -1,0 或 1。
【特殊之处:不平衡标识 + 高度计算】在下面这个算法中有个比较特殊的地方,他是将判断因素加入到高度计算中了。(在高度中 ,以 取出 -1 作为不平衡的标识,出现差的绝对值大于1的时候,则归纳到-1.)
public boolean isBalanced(TreeNode root) {
if(root==null){
return true;
}
return height(root)!=-1;
}
public int height(TreeNode node){
if(node==null){
return 0;
}
int lH=height(node.left);
if(lH==-1){
return -1;
}
int rH=height(node.right);
if(rH==-1){
return -1;
}
if(lH-rH<-1 || lH-rH>1){
return -1;
}
return Math.max(lH,rH)+1;
}
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.
分析及解答
【平衡因子】
某结点的左子树与右子树的高度(深度)差即为该结点的平衡因子(BF,Balance Factor)。
平衡二叉树上所有结点的平衡因子只可能是 -1,0 或 1。
【特殊之处:不平衡标识 + 高度计算】在下面这个算法中有个比较特殊的地方,他是将判断因素加入到高度计算中了。(在高度中 ,以 取出 -1 作为不平衡的标识,出现差的绝对值大于1的时候,则归纳到-1.)
public boolean isBalanced(TreeNode root) {
if(root==null){
return true;
}
return height(root)!=-1;
}
public int height(TreeNode node){
if(node==null){
return 0;
}
int lH=height(node.left);
if(lH==-1){
return -1;
}
int rH=height(node.right);
if(rH==-1){
return -1;
}
if(lH-rH<-1 || lH-rH>1){
return -1;
}
return Math.max(lH,rH)+1;
}
相关文章推荐
- leetcode_110. Balanced Binary Tree 判断一棵二叉树是否为平衡二叉树
- Leetcode#110. Balanced Binary Tree(判断是否是平衡二叉树)
- LeetCode-Balanced Binary Tree && 二叉树的深度 && 二叉树的平衡
- leetcode 110. Balanced Binary Tree 判断是否是一颗平衡二叉树
- 二叉树的深度&判断一棵二叉树是否是平衡二叉树&110. Balanced Binary Tree
- 【遍历二叉树】10判断二叉树是否平衡【Balanced Binary Tree】
- 【LeetCode】110. Balanced Binary Tree-判断是否为平衡二叉树
- LeetCode(Balanced Binary Tree ) 判断一个二叉树是否为平衡二叉树
- 110. Balanced Binary Tree 判定是否平衡
- 二叉树递归问题 leetcode 572. Subtree of Another Tree & leetcode 110. Balanced Binary Tree
- 110.LeetCode Balanced Binary Tree(easy)[二叉树 检测是否平衡]
- 【LeetCode 110_二叉树_遍历】Balanced Binary Tree
- 【LeetCode】110. Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree 递归求解
- [LeetCode] 110. Balanced Binary Tree 解题思路
- LeetCode 98 Validate Binary Search Tree判断是否为合法二叉树
- leetcode 110. Balanced Binary Tree
- leetCode 110.Balanced Binary Tree (平衡二叉树) 解题思路和方法
- [leetcode] 110. Balanced Binary Tree 解题报告
- 【LeetCode】110. Balanced Binary Tree