zoukankan      html  css  js  c++  java
  • LeetCode Balanced Binary Tree

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isBalanced(TreeNode *root) {
            int h;
            return dfs(root, h);
        }
        
        bool dfs(TreeNode* root, int& height) {
            height = 0;
            if (root == NULL) {
                return true;
            }
            int lh, rh;
            if (!dfs(root->left, lh)) return false;
            if (!dfs(root->right, rh)) return false;
            lh++, rh++;
            int diff = lh - rh;
            if (diff < -1 || diff > 1) return false;
            if (diff < 0) {
                height =  rh;
            } else {
                height =  lh;
            }
            return true;
        }
    };

     第二轮:

    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.

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    private:
        bool valid;
    public:
        bool isBalanced(TreeNode *root) {
            valid = true;
            height(root);
            return valid;
        }
        
        int height(TreeNode* root) {
            if (!valid || root == NULL) {
                return 0;
            }
            int hl = height(root->left);
            int hr = height(root->right);
            int diff = max(hl, hr) - min(hl, hr);
            if (diff > 1) {
                valid = false;
            }
            return max(hl, hr) + 1;
        }
    };

     再简化一下:

    /**
     * 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) {
            return height(root) >= 0;
        }
        
        int height(TreeNode* root) {
            if (root == NULL) {
                return 0;
            }
            int lh = height(root->left);
            int rh = height(root->right);
            if (lh < 0 || rh < 0 || abs(lh - rh) > 1) {
                return -1;
            }
            return 1 + max(lh, rh);
        }
    };
  • 相关阅读:
    还得还得学啊
    感觉自己写的东西很死板啊
    好烦啊,不知道选哪个?
    222
    111
    愁人啊
    ssm+ajax实现登陆
    ssm框架搭建
    抽象类与接口
    代理设计模式
  • 原文地址:https://www.cnblogs.com/lailailai/p/3805072.html
Copyright © 2011-2022 走看看