Leetcode 110 判断一颗二叉树是否是平衡二叉树

题解:根据平衡二叉树的定义,左右子树的高度差不超过1。用递归。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int heightTree(TreeNode* root){
        if(root==NULL){
            return 0;
        }
        else if(root->left==NULL&&root->right==NULL){
            return 1;
        }
        else{
            return max(heightTree(root->left),heightTree(root->right))+1;
        }
    }
    bool isBalanced(TreeNode* root) {
        if(root==NULL){
            return true;
        }
        if(abs(heightTree(root->left)-heightTree(root->right))>1){
            return false;
        }
        return isBalanced(root->left)&&isBalanced(root->right);
    }
};

耗时16ms.

    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/patkritlee/article/details/50659751
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞