二分木がバランスの取れた二分木であるかどうかを判断する
トピックの説明
高さバランスのとれた二分木は次のように定義されます。二分木の各ノードの左右のサブツリー間の高さの差の絶対値は 1 を超えません。
例
原題 OJリンク
https://leetcode.cn/problems/balances-binary-tree/
応答コード
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
import java.lang.Math;
class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null){
return true;
}
int leftH = getHeight(root.left);
int rightH = getHeight(root.right);
if((Math.abs(leftH-rightH)<=1) && isBalanced(root.left) && isBalanced(root.right)){
return true;
}
return false;
}
public int getHeight(TreeNode root){
//求树的深度(高度)
if(root == null){
return 0;
}
if(root.right == null && root.left == null){
return 1;
}
// int count1 = getHeight(root.left)+1;
// int count2 = getHeight(root.right)+1;
// return Math.max(count1,count2);
return Math.max(getHeight(root.left)+1, getHeight(root.right)+1);
}
}
このコードの欠点の 1 つは、実際には多くの繰り返し作業を行うことです。実際、二重層の再帰を実行しています。各ノードは、その左と右のサブツリーの高さを計算します。不満の差の絶対値が小さい場合にのみ実行されます。 1 以上の場合は false を返しますが、実際には、この作業は高さを計算するときに直接行うことができます。左右のサブツリーの高さの差の絶対値が 1 より大きい場合は、直接 -1 を返します。後続のノードの高さは、ツリーがアンバランスである必要があることを示しているため、まったく計算する必要はありません。
したがって、次のコードがあります
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
import java.lang.Math;
class Solution {
public boolean isBalanced(TreeNode root) {
return maxDepth(root)>=0;
}
public int maxDepth(TreeNode root){
if(root == null){
return 0;
}
int count1 = maxDepth(root.left);
if(count1<0){
return-1;
}
int count2 = maxDepth(root.right);
if(count2<0){
return -1;
}
if(Math.abs(count1-count2)<=1){
return Math.max(count1,count2)+1;
}
else{
return -1;
}
}
}