[LeetCode]--Balanced Binary Tree

题目

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

中文题意:判断一个二叉树是否为平衡二叉树。平衡二叉树指二叉树中所有节点的两个子树的深度相差不超过1。

分析

       由题意可知,该问题可以用DFS的思想解决。首先一棵二叉树的深度取决于深度较大的子树,也即我们需要判断以一个根节点的两个子节点为根的树的深度,而一棵二叉树的总深度则可以通过递归的方式得到。
       实现了二叉树深度的函数,我们即可通过调用该函数,求出两棵子树的深度,再递归判断其是否相差不超过1,最终得出所给二叉树是否为平衡二叉树的结果。
       注意,我们要特别考虑根节点为空的情况,当根节点点为空时,二叉树深度为0,是平衡二叉树。
       该算法的时间复杂度为O(n),其中n为二叉树中节点数目。

解答

/**
 * 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 depth(TreeNode* r){
        if(r==NULL)
            return 0;
        else return max(depth(r->left),depth(r->right))+1;
    }
    bool isBalanced(TreeNode* root) {
        if(root==NULL){
            return true;
        }
        int left_depth=depth(root->left);
        int right_depth=depth(root->right);
        int diff=abs(left_depth-right_depth);
        if(diff<=1 && isBalanced(root->left) && isBalanced(root->right))
            return true;
        else return false;
    }
};


猜你喜欢

转载自blog.csdn.net/weixin_38057349/article/details/79118259