LeetCode 面试题55 - II. 平衡二叉树(树的高度的预处理、DFS)

在这篇博客平衡二叉树里,时间复杂为O(nn)O(n*n)
原因是,每一次计算高度时,都要去遍历树。
如果用O(n)O(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:
    bool isBalanced(TreeNode* root) {
        getHeight(root);
        return dfs(root);    
    }
    bool dfs(TreeNode *root){
        if(!root){
            return true;
        }
        int lh = root->left?root->left->val:0;
        int rh = root->right?root->right->val:0;
        if(abs(lh-rh)>1) return false;
        if(!dfs(root->left) || !dfs(root->right)) return false;
        return true;
    }
    int getHeight(TreeNode *root){
        if(!root) return 0;
        return root->val=1+max(getHeight(root->left),getHeight(root->right));
    }

};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章