leetCode 110. Balanced Binary Tree 平衡二叉树

简介:

110. 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. 做一个辅助函数来求的树的高度。

  2. 通过辅助函数来递归求解。


代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
  * 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 :
     int  depth(TreeNode* root)
     {
         if (!root)
             return  0;
         int  l = depth(root->left) ;
         int  r = depth(root->right) ;
         return  1 + ((l > r)?l:r);
     }
     bool  isBalanced(TreeNode* root) {
         if (!root)
             return  true ;
         else
         {
             int  l = depth(root->left);
             int  r = depth(root->right);
             if (l + 1 < r || r + 1 <l)
             {
                 return  false ;
             }
             else
                 return  (isBalanced(root->left) && isBalanced(root->right) );
         }
     }
};



本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1835477
相关文章
|
5月前
|
算法
【LeetCode题目详解】(五)144.二叉树的前序遍历、94.二叉树的中序遍历、145.二叉树的后序遍历、104.二叉树的最大深度、110.平衡二叉树
【LeetCode题目详解】(五)144.二叉树的前序遍历、94.二叉树的中序遍历、145.二叉树的后序遍历、104.二叉树的最大深度、110.平衡二叉树
31 0
LeetCode | 110. 平衡二叉树
LeetCode | 110. 平衡二叉树
LeetCode刷题Day14——二叉树(完全二叉树、平衡二叉树、二叉树路径、左叶子之和)
一、完全二叉树的节点个数 题目链接:222. 完全二叉树的节点个数
|
5月前
|
算法
代码随想录算法训练营第十七天 | LeetCode 110. 平衡二叉树、257. 二叉树的所有路径、404. 左叶子之和
代码随想录算法训练营第十七天 | LeetCode 110. 平衡二叉树、257. 二叉树的所有路径、404. 左叶子之和
28 0
|
6月前
【Leetcode -110.平衡二叉树 -226.翻转二叉树】
【Leetcode -110.平衡二叉树 -226.翻转二叉树】
17 0
|
11月前
Leetcode 110 平衡二叉树
Leetcode 110 平衡二叉树
145 0
|
算法
LeetCode 周赛 340,质数 / 前缀和 / 极大化最小值 / 最短路 / 平衡二叉树
今天讲 LeetCode 单周赛第 340 场,今天状态不好,掉了一波大分。
57 0
代码随想录刷题|LeetCode 110.平衡二叉树 257.二叉树的所有路径 404.左叶子之和
代码随想录刷题|LeetCode 110.平衡二叉树 257.二叉树的所有路径 404.左叶子之和
【leetcode-剑指 Offer 55 - II】平衡二叉树
题目 输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。 示例 1: 给定二叉树 [3,9,20,null,null,15,7]
【leetcode-剑指 Offer 55 - II】平衡二叉树