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
这里先实现一个辅助函数,计算二叉树的深度;
最后采用递归的思想来完成;
- class Solution { 
- public: 
- bool isBalanced(TreeNode* root) 
- { 
- if (root==NULL) 
- { 
- return true; 
- } 
- int left = help(root->left); 
- int right = help(root->right); 
- if (left-right>=-1 && left-right<=1) 
- { 
- if (isBalanced(root->left) && isBalanced(root->right)) 
- { 
- return true; 
- } 
- } 
- return false; 
- } 
- int help(TreeNode* root) 
- { 
- if (root==NULL) 
- { 
- return 0; 
- } 
- if (root->left==NULL && root->right==NULL) 
- { 
- return 1; 
- } 
- return max(help(root->left), help(root->right)) + 1; 
- } 
- }; 

 
					
				
 
			
			
			
						
			 
					
				 我要赚赏金
 我要赚赏金 STM32
STM32 MCU
MCU 通讯及无线技术
通讯及无线技术 物联网技术
物联网技术 电子DIY
电子DIY 板卡试用
板卡试用 基础知识
基础知识 软件与操作系统
软件与操作系统 我爱生活
我爱生活 小e食堂
小e食堂

