LeetCode 110.平衡二叉树
题目链接:https://leetcode.cn/problems/balanced-binary-tree/
题目
解答
递归法
class Solution {
public:
//返回该节点为根节点的二叉树的高度,如果不是平衡二叉树则返回-1
int getDepth(TreeNode* node){
if(node == NULL) return 0;
int leftDepth = getDepth(node->left);
if(leftDepth == -1) return -1;
int rightDepth = getDepth(node->right);
if(rightDepth == -1) return -1;
// int result;
// if(abs(leftDepth - rightDepth) > 1){
// result = -1;
// } else {
// result = 1 + max(leftDepth, rightDepth);
// }
// return result;
return abs(leftDepth - rightDepth) > 1 ? -1 : 1 + max(leftDepth, rightDepth);
}
bool isBalanced(TreeNode* root) {
return getDepth(root) == -1 ? false : true;
}
};