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

  • 相关阅读:
    tomcat2章1
    tomcat1章1
    线程安全的CopyOnWriteArrayList
    Java Security: Illegal key size or default parameters?
    struct和typedef struct
    C可变参数函数 实现
    C和C++混合编程(__cplusplus 与 external "c" 的使用)
    WebRTC之带宽控制部分学习(1) ------基本demo的介绍
    WebRTC代码走读(八):代码目录结构
    webrtc中的带宽自适应算法
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5425720.html
Copyright © 2011-2022 走看看