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;
            
            
        }
    };
  • 相关阅读:
    C#连接数据库的三种方法
    远程控制mysql出现的问题
    DFS_子集
    DFS_全排列
    Centos下搭建Mysql
    Nginx与PHP(FastCGI)的安装、配置与优化
    Centos下主DNS的搭建
    Nginx的基本配置与优化
    Nginx服务器的安装与配置
    gdb基本命令
  • 原文地址:https://www.cnblogs.com/obama/p/3256086.html
Copyright © 2011-2022 走看看