标签:
实现一个函数,检查二叉树是否平衡,平衡的定义如下,对于树中的任意一个结点,其两颗子树的高度差不超过1。
给定指向树根结点的指针TreeNode* root,请返回一个bool,代表这棵树是否平衡。
思想:分治法(手段) 递归(处理方法)
代码如下:
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
public class Balance {
public boolean isBalance(TreeNode root) {
if(root==null) return true;
boolean lef= isBalance(root.left);
boolean rig=isBalance(root.right);
int lefLength=deepth(root.left);
int rigLength=deepth(root.right);
if(lef && rig && Math.abs(lefLength-rigLength)<=1)
return true;
else
return false;
}
int deepth(TreeNode root){
if(root==null) return 0;
int leftDeepth=deepth(root.left);
int rightDeepth=deepth(root.right);
return Math.max(leftDeepth,rightDeepth)+1;
}
}
标签:
原文地址:http://www.cnblogs.com/mlz-2019/p/4769025.html