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;
            }
        }
    };
  • 相关阅读:
    11月28日总结
    12月06日总结
    12月02日总结
    11月26日总结
    12月05日总结
    11月30日总结
    软件设计职责链模式
    软件设计策略模式
    软件设计组合模式
    大数据竞赛练习题二
  • 原文地址:https://www.cnblogs.com/zengzy/p/5053031.html
Copyright © 2011-2022 走看看