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

  • 相关阅读:
    JS-字符串截取方法slice、substring、substr的区别
    Vue中computed和watch的区别
    Vue响应式原理及总结
    JS实现深浅拷贝
    JS中new操作符源码实现
    点击页面出现爱心效果
    js判断对象是否为空对象的几种方法
    深入浅出js实现继承的7种方式
    es6-class
    详解 ESLint 规则,规范你的代码
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5425720.html
Copyright © 2020-2023  润新知