美文网首页
110. Balanced Binary Tree

110. Balanced Binary Tree

作者: 刘小小gogo | 来源:发表于2018-08-17 08:15 被阅读0次
    image.png

    解法一:由上至下

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

    解法二:dfs

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

    相关文章

      网友评论

          本文标题:110. Balanced Binary Tree

          本文链接:https://www.haomeiwen.com/subject/fazabftx.html