110. 平衡二叉树

一、递归

单次递归时,判断左右子树是否是平衡树,若不是,返回-1,若是,但输得出高度

  1. class Solution {
  2. public:
  3. // 返回以该节点为根节点的二叉树的高度,如果不是二叉搜索树了则返回-1
  4. int getHeight(TreeNode* node) {
  5. if (node == NULL) {
  6. return 0;
  7. }
  8. int leftHeight = getHeight(node->left);
  9. if (leftHeight == -1) return -1;
  10. int rightHeight = getHeight(node->right);
  11. if (rightHeight == -1) return -1;
  12. return abs(leftHeight - rightHeight) > 1 ? -1 : 1 + max(leftHeight, rightHeight);
  13. }
  14. bool isBalanced(TreeNode* root) {
  15. return getHeight(root) == -1 ? false : true;
  16. }
  17. };