剣指_へいこうにじゅ
タイトル
ツリーを入力し、ツリーがバランスツリーであるかどうかを判断します.
構想:本題は後序遍歴を利用して、サブツリーのバランス性を優先的に考察することができ、サブツリーがバランスしていない場合、この二叉木は必ずバランスが取れない.
コード1(476 k,3 ms)
コード(484 k,3 ms)
ツリーを入力し、ツリーがバランスツリーであるかどうかを判断します.
構想:本題は後序遍歴を利用して、サブツリーのバランス性を優先的に考察することができ、サブツリーがバランスしていない場合、この二叉木は必ずバランスが取れない.
コード1(476 k,3 ms)
class Solution {
public:
int getdepth(TreeNode* root){
if(root==NULL)
return 0;
int left=getdepth(root->left);
if(left==-1)
return -1;
int right=getdepth(root->right);
if(right ==-1)
return -1;
if(left-right>1||left-rightright?left+1:right+1;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
return getdepth(pRoot)!=-1;
}
};
コード(484 k,3 ms)
class Solution {
public:
bool isBalanced=true;
int getdepth(TreeNode* root){
if(root==NULL)
return 0;
int left=getdepth(root->left);
int right=getdepth(root->right);
if(left-right>1||left-rightright?left+1:right+1;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
getdepth(pRoot);
return isBalanced;
}
};