leetCode 110. Balanced Binary Tree 平衡二叉树

发布时间:2020-06-26 00:08:06 作者:313119992
来源:网络 阅读:467

110. 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. 做一个辅助函数来求的树的高度。

  2. 通过辅助函数来递归求解。


代码如下:

/**
 * 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* root)
    {
        if(!root)
            return 0;
        int l = depth(root->left) ;
        int r = depth(root->right) ;
        return 1 + ((l > r)?l:r);
    }
    bool isBalanced(TreeNode* root) {
        if(!root)
            return true;
        else
        {
            int l = depth(root->left);
            int r = depth(root->right);
            if(l + 1 < r || r + 1 <l)
            {
                return false;
            }
            else
                return (isBalanced(root->left) && isBalanced(root->right) );
        }
    }
};


2016-08-08 00:25:26

推荐阅读:
  1. leetcode--二叉树的层次遍历
  2. leetcode--翻转二叉树

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

二叉树 ce

上一篇:mac上亲测的好用终端命令

下一篇:用PuTTY SSH 密钥生成工具puttygen.exe生成密钥.

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》