判断一棵树是否是AVL树 LeetCode110. Balanced Binary Tree

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Yonggie/article/details/89442935

请注意树节点的结构

代码很水,主要是写法。

/**
 * 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 getDepth(TreeNode *root,int depth){
        if(!root) return depth;
        
        int left=getDepth(root->left,depth+1);
        int right=getDepth(root->right,depth+1);
        return max(left,right);
   
    }
    bool isBalanced(TreeNode* root) {
        if(!root) return true;
        int left=getDepth(root->left,1);
        int right=getDepth(root->right,1);
//这个节点的左子树和右子树高度不超过1,而且它所有的子节点都不超过1,直接进行前序遍历就行。
        return abs(left-right)<=1&&isBalanced(root->left)&&isBalanced(root->right);
    }
};

猜你喜欢

转载自blog.csdn.net/Yonggie/article/details/89442935
今日推荐