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

    1.题目描述

    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.

    2.解法分析

    判断一个树是否为平衡二叉树与求树的深度如出一辙,只是返回值有两个,一个是当前树是否为平衡二叉树,另一个是当前树的高度。

    /**
     * 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) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(!root)return true;
            
            int depth;
            
            return myJudge(root,depth);
        }
        
        bool myJudge(TreeNode *root,int &depth)
        {
            if(root==NULL)
            {
               depth=0;return true;
            }
            
            int depth_left;
            int depth_right;
            
            bool lj=myJudge(root->left,depth_left);
            if(!lj)return false;
            bool rj=myJudge(root->right,depth_right);
            if(!rj)return false;
     
            depth = max(depth_left,depth_right)+1;
            
            if((depth-1-min(depth_left,depth_right))<=1)return true;
            else return false;
            
            
        }
    };
  • 相关阅读:
    校验规则,纯数字。几位有效数字,保留几位小数
    银行卡校验规则(Luhn算法)
    forEach兼容ie8
    node.js
    gulp
    observer
    webpack.config.js 配置
    内存泄漏(Memory Leak)
    cdn
    前端 各种插件的官网
  • 原文地址:https://www.cnblogs.com/obama/p/3256086.html
Copyright © 2011-2022 走看看