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) ) ;
            }
        }
       
    };

  • 相关阅读:
    Navicat 远程连接ubuntu出现的问题
    替换 ubuntu 自带的python版本
    xpath疑惑
    xpath中返回值问题
    AttributeError: 'unicode' object has no attribute 'xpath'
    linux下mysql忘记密码解决方案
    IntelliJ idea常用快捷键
    最近的说明(本篇不谈具体技术,看技术的可以忽略)
    常用的排序算法介绍和在JAVA的实现(二)
    mysql数据库查询过程探究和优化建议
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5425720.html
Copyright © 2011-2022 走看看