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

    Balanced Binary Tree

    Total Accepted: 86508 Total Submissions: 263690 Difficulty: Easy

    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 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  getTreeHeight(TreeNode* root){
            if(root==NULL){
                return 0;
            }
            int lh = getTreeHeight(root->left);
            int rh = getTreeHeight(root->right);
            return lh>rh ? lh+1:rh+1;
        }
        bool isBalanced(TreeNode* root) {
            if(root==NULL){
                return true;
            }
            int lh = getTreeHeight(root->left);
            int rh = getTreeHeight(root->right);
            if(fabs(lh-rh)<=1){
                return isBalanced(root->left) && isBalanced(root->right);
            }else{
                return false;
            }
        }
    };
  • 相关阅读:
    1015
    1016
    1014
    1002
    1010
    1006
    动态规划1001
    动态规划1002
    使用EF框架调用带有输出参数(output)的存储过程
    工程地质相关知识
  • 原文地址:https://www.cnblogs.com/zengzy/p/5053031.html
Copyright © 2011-2022 走看看