溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

leetCode 110. Balanced Binary Tree 平衡二叉樹

發(fā)布時(shí)間:2020-06-26 00:08:06 來源:網(wǎng)絡(luò) 閱讀:548 作者:313119992 欄目:編程語言

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. 做一個(gè)輔助函數(shù)來求的樹的高度。

  2. 通過輔助函數(shù)來遞歸求解。


代碼如下:

/**
 * 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

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI