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.
Given the following tree [3,9,20,null,null,15,7]:
Return true.
思路:这道题需要判断给一个root,是不是平衡二叉树
判断平衡二叉树的标准是左右子树高度之差不大于1,左右子树都分别平衡,所以不仅要判断,还要有高度进行判断,自己新建一个新的数据类型resultType:
class resultType{
public boolean isBal;
public int maxdepth;
public resultType(boolean isBal,int maxdepth){
this.isBal=isBal;
this.maxdepth=maxdepth;
}
}
然后进行遍历,出口是root遍历到叶子节点,有以下几种情况:
- 左右都不平衡
- root这里就不平衡:左右子树高度之差大于1
- 平衡
如果平衡的话,返回true,高度是左右子树最大高度+1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//返回需要返回两个值,一个是否为平衡二叉树,一个是计算二叉树高度
class resultType{
public boolean isBal;
public int maxdepth;
public resultType(boolean isBal,int maxdepth){
this.isBal=isBal;
this.maxdepth=maxdepth;
}
}
public class Solution {
//平衡二叉树:左右子树之差不大于一
public boolean isBalanced(TreeNode root) {
return helper(root).isBal;
}
//1.定义:以root为根的二叉树是否平衡,以及它的高度为多少
private resultType helper(TreeNode root){
//3.出口:叶子节点
if(root==null){
return new resultType(true,0);
}
//2.split
resultType left=helper(root.left);
resultType right=helper(root.right);
//if subtree is not banlanced
if(!left.isBal||!right.isBal){
return new resultType(false,1);
}
//if the root are not balanced
if(Math.abs(left.maxdepth-right.maxdepth)>1){
return new resultType(false,1);
}
//if balance
int dep=Math.max(left.maxdepth,right.maxdepth)+1;
return new resultType(true, dep);
}
}