110:Balanced Binary Tree【樹】【DFS】

題目鏈接:click~

/*題意:判斷一顆平衡二叉樹是否平衡*/

/**
 *思路:平衡二叉樹的每個結點的左右子樹的深度差不超過1
 *      DFS記錄每個結點的左右子樹的深度,判斷是否平衡
 */

class Solution {

public:
    bool Judge(TreeNode *T, int &dep) {
        if(T == NULL) {
            dep = 0;
            return true;
        }

        int leftdepth, rightdepth;
        bool leftBalance = Judge(T->left, leftdepth);
        bool rightBalance = Judge(T->right, rightdepth);

        dep = max(leftdepth, rightdepth) + 1;

        return leftBalance && rightBalance && (abs(leftdepth-rightdepth) <= 1);
    }
    bool isBalanced(TreeNode *root) {
        int dep;
        return Judge(root, dep);
    }
};


發佈了185 篇原創文章 · 獲贊 10 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章