大家觉得写还可以,可以点赞、收藏、关注一下吧!
也可以到我的个人博客参观一下,估计近几年都会一直更新!和我做个朋友吧!https://motongxue.cn
110. 平衡二叉树
题目描述
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
示例
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true 。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
1
/ \
2 2
/ \
3 3
/ \
4 4
返回 false 。
分析
- 前导知识:平衡树(Balance Tree,BT) 指的是,任意节点的子树的高度差都小于等于1。
- 那么我们就写一个求树高度的函数
getDeepth
- 求出根节点两子树高度差是否小于1
Math.abs(getDeep(root.left)-getDeep(root.right))<=1
- 看看左右子树是否平衡(递归完成)
isBalanced(root.left)(root.right)
代码实现
/*
* @Author: motongxue
* @Date: 2020-08-16 23:22:46
* @LastEditors: motongxue
* @LastEditTime: 2020-08-16 23:38:39
* @Blog: https://motongxue.cn
* @Description: file content
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int getDeep(TreeNode root){
if(root == null) return 0;
int leftDeepth = getDeep(root.left)+1;
int rightDeepth = getDeep(root.right)+1;
return Math.max(leftDeepth,rightDeepth);
}
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
return isBalanced(root.left)
&&isBalanced(root.right)
&&Math.abs(getDeep(root.left)-getDeep(root.right))<=1;
}
}
- 时间复杂度: O ( n 2 ) O(n ^ 2) O(n2),其中 n 是二叉树中的节点个数。
- 空间复杂度: O ( n ) O(n) O(n),其中 n 是二叉树中的节点个数。空间复杂度主要取决于递归调用的层数,递归调用的层数不会超过 n。
提交结果
2020年8月17日更
大家觉得写还可以,可以点赞、收藏、关注一下吧!
也可以到我的个人博客参观一下,估计近几年都会一直更新!和我做个朋友吧!https://motongxue.cn