leetcode - Balanced Binary Tree

本文介绍了一种判断二叉树是否平衡的方法,并提供了一个C++实现示例。平衡二叉树定义为对于任意节点,其左右子树的高度差不超过1。通过递归计算每个节点的左右子树高度来判断整棵树是否满足平衡条件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目: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、判断每个节点(子树)的高度差,高度差在绝对值为1的范围内便是平衡二叉树

2、可以适当改造计算树高度的方法,即树的高度为左子树与右子树高度较大者加1

 

代码:

 1 #include <stddef.h>
 2 #include <iostream>
 3 /**
 4  * Definition for binary tree
 5  * struct TreeNode {
 6  *     int val;
 7  *     TreeNode *left;
 8  *     TreeNode *right;
 9  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
10  * };
11  */
12 
13 struct TreeNode
14 {
15     int val;
16     TreeNode *left;
17     TreeNode *right;
18     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
19 };
20 
21 class Solution
22 {
23 public:
24     bool isBalanced(TreeNode *root)
25     {
26         balanced = true;
27         getDepth(root);
28 
29         return balanced;
30     }
31     int getDepth(TreeNode *root)
32     {
33         if (root == NULL)
34         {
35             return 0;
36         }
37 
38         int leftDepth = getDepth(root->left);
39         int rightDepth = getDepth(root->right);
40 
41         if (leftDepth - rightDepth > 1 || leftDepth - rightDepth < -1)
42         {
43             balanced = false;
44         }
45 
46         return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
47     }
48 private:
49     bool balanced;
50 };
51 
52 int main()
53 {
54     TreeNode *root = new TreeNode(1);
55     root->right = new TreeNode(1);
56     root->right->right = new TreeNode(1);
57     Solution s;
58     s.isBalanced(root);
59     std::cout << root->val << std::endl << root->right->val << std::endl << root->right->val << std::endl;
60     system("pause");
61 
62     return 0;
63 }
View Code

 

 上网搜了一些帖子,方法都是类似,就不贴出来了

转载于:https://www.cnblogs.com/laihaiteng/p/3795408.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值