zoukankan      html  css  js  c++  java
  • Leetcode题目:Balanced Binary Tree

    题目:

    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.

    题目解答:判断一棵给定的二叉树是不是平衡二叉树。平衡二叉树的条件有:

        它是一棵空树或它的左右两个子树的高度差的绝对值不超过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) {
            if(root == NULL)
                return true;
            if((root -> left == NULL ) && (root -> right == NULL))
                return true;
            int leftDepth = 0;
            int rightDepth = 0;
            return isSubBalance(root -> left,leftDepth) && isSubBalance(root -> right , rightDepth) && (abs(leftDepth - rightDepth) <= 1) ;
        }
       
        bool isSubBalance(TreeNode *root,int &depth)
        {
            if(root == NULL)
            {
                depth = 0;
                return true;
            }
            if((root -> left == NULL ) && (root -> right == NULL))
            {
                depth = 1;
                return true;
            }
            else
            {
                depth = 1;
                int leftDepth = 0;
                int rightDepth = 0;
                return isSubBalance(root -> left,leftDepth) && isSubBalance(root -> right , rightDepth) && (abs(leftDepth - rightDepth) <= 1) && (depth += max(leftDepth,rightDepth) ) ;
            }
        }
       
    };

  • 相关阅读:
    .NET 面试题汇总(带答案)
    C#声明一个100大小的数组 随机生成1-100之间不重复的数
    添加和读取Resources嵌入资源文件(例如.dll和.ssk文件)
    C#DataTable转List<T>互转
    “不允许使用邮箱名称。服务器响应为:”的错误解决办法
    微信多开防撤回(带提示)2.8.0.133补丁
    逆向某网站的登录接口生成元素加密
    C#中new的三种用法
    SQL Server查询第31到40条数据
    关于EF框架EntityState的几种状态
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5425720.html
Copyright © 2011-2022 走看看