加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

LeetCode110平衡二叉树-C语言

发布时间:2020-12-15 04:52:55 所属栏目:百科 来源:网络整理
导读:给定一个二叉树,判断它是否是高度平衡的二叉树。 本题中,一棵高度平衡二叉树定义为: 一个二叉树每个节点?的左右两个子树的高度差的绝对值不超过1。 示例 1: 给定二叉树?[3,9,20,null,15,7] 3 / 9 20 / 15 7 返回?true?。 示例 2: 给定二叉树?[1,2,3,4,4]

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点?的左右两个子树的高度差的绝对值不超过1。

示例 1:

给定二叉树?[3,9,20,null,15,7]

3

/

9 20

/

15 7

返回?true?。


示例 2:

给定二叉树?[1,2,3,4,4]

1

/

2 2

/

3 3

/

4 4

返回?false?。

/**

* Definition for a binary tree node.

* struct TreeNode {

* int val;

* struct TreeNode *left;

* struct TreeNode *right;

* };

*/

int depth(struct TreeNode *t){

int l_depth = 0,r_depth = 0,diff;

if(t == NULL) return 0;

else{

l_depth = depth(t -> left) + 1;

r_depth = depth(t -> right) + 1;

}

int depth = l_depth > r_depth ? l_depth : r_depth;

return depth;

}

bool isBalanced(struct TreeNode* root) {

//对每个根节点,递归计算二叉树左子树与右子树深度之差

int l,r;

if(root == NULL) return true;

l = depth(root -> left);

r = depth(root -> right);

if(abs(l - r) > 1) return false;

return isBalanced(root -> left) && isBalanced(root -> right);

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读