leetcode【DFS】-----110. Balanced Binary Tree(平衡二叉树)

1、题目描述

     

2、分析

     判断平衡二叉树只需要计算其左右子树的高然后相减只要其值小于1即可。只有左右子树都满足时才返回真。

3、代码

/**
 * 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:
    bool isBalanced(TreeNode* root) {
        if(root==NULL) return true;
        int heightleft=heigh(root->left);
        int heightright=heigh(root->right);
        int res=abs(heightleft-heightright);
        if(res>1) return false;
         return isBalanced(root->left)&&isBalanced(root->right);
    }
    int heigh(TreeNode* root){
        if(root==NULL)
            return 0;
        return 1+max(heigh(root->left),heigh(root->right));        
    }
};

4、相关知识点

        求树的高度的方法。

posted @ 2019-07-09 21:14  吾之求索  阅读(107)  评论(0)    收藏  举报