《leetCode》:Balanced Binary Tree
3560 ワード
タイトル
構想
ステップ1:親ノードが高度にバランスしているかどうかを判断し、そうでない場合はfalseを返します.もしそうであれば,その左右のサブノードが高度にバランスしているかどうかを判断し続ける.一方,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:親ノードが高度にバランスしているかどうかを判断し、そうでない場合はfalseを返します.もしそうであれば,その左右のサブノードが高度にバランスしているかどうかを判断し続ける.一方,1つのノードが高さバランスであるか否かを判断すると,そのノードの左右のサブツリーの高さ差を求めることに転化する.
実装コードは次のとおりです.
#include<stdio.h>
#include<stdlib.h>
/** * Definition for a binary tree node.*/
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
// : , 1.
int max(int a,int b){
return (a>=b)?a:b;
}
int nodeDepth(struct TreeNode* root){
if(root==NULL){
return 0;
}
//
int leftSubNodeDepth=nodeDepth(root->left);
int rightSubNodeDepth=nodeDepth(root->right);
return max(leftSubNodeDepth,rightSubNodeDepth)+1;
}
bool isBalancedHelper(struct TreeNode* root){
if(root==NULL){
return true;
}
//
int dif=nodeDepth(root->left)-nodeDepth(root->right);
if(dif>1||dif<-1){// 1 false
return false;
}
//
return isBalancedHelper(root->left)&&isBalancedHelper(root->right);
}
bool isBalanced(struct TreeNode* root) {
if(root==NULL){
return true;
}
return isBalancedHelper(root);
}