码迷,mamicode.com
首页 > 其他好文 > 详细

110 Balanced Binary Tree 平衡二叉树

时间:2018-04-05 01:13:24      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:pre   efi   nbsp   定义   return   abs   pos   一个   高度   

给定一个二叉树,确定它是高度平衡的。
对于这个问题,一棵高度平衡二叉树的定义是:
一棵二叉树中每个节点的两个子树的深度相差不会超过 1。
案例 1:
给出二叉树 [3,9,20,null,null,15,7]:
    3
   / \
  9  20
    /  \
   15   7
返回 true 。
案例 2:
给出二叉树 [1,2,2,3,3,null,null,4,4]:
       1
      / \
     2   2
    / \
   3   3
  / \
 4   4
返回 false 。
详见:https://leetcode.com/problems/balanced-binary-tree/description/

/**
 * 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 isBalance=true;
    bool isBalanced(TreeNode* root) {
        if(root==nullptr)
        {
            return true;
        }
        getDepth(root);
        return isBalance;
    }
    int getDepth(TreeNode* root)
    {
        if(root==nullptr)
        {
            return 0;
        }
        int left=getDepth(root->left);
        int right=getDepth(root->right);
        if(abs(left-right)>1)
        {
            return isBalance=false;
        }
        return max(left,right)+1;
    }
};

 

110 Balanced Binary Tree 平衡二叉树

标签:pre   efi   nbsp   定义   return   abs   pos   一个   高度   

原文地址:https://www.cnblogs.com/xidian2014/p/8719481.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!