110. Balanced Binary Tree
- Total Accepted: 119517
- Total Submissions:345415
- Difficulty: Easy
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且左右子树都是平衡树。
方法二:设计了isDepth函数:如果root为根的树是平衡树,则返回树高;否则返回-1。
代码:
方法一:
1 class Solution { 2 public: 3 int Depth(TreeNode* root){ 4 if(!root){ 5 return 0; 6 } 7 return 1+max(Depth(root->left),Depth(root->right)); 8 } 9 bool isBalanced(TreeNode* root) { 10 if(!root){ 11 return true; 12 } 13 int left=Depth(root->left); 14 int right=Depth(root->right); 15 return abs(left-right)<=1&&isBalanced(root->left)&&isBalanced(root->right); 16 } 17 };
方法二:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 //如果root为根的树是平衡树,则返回树高;否则返回-1 13 int isDepth(TreeNode* root){ 14 if(!root){ 15 return 0; 16 } 17 int left=isDepth(root->left); 18 if(left==-1) return -1; 19 int right=isDepth(root->right); 20 if(right==-1) return -1; 21 if(abs(left-right)<=1){ 22 return max(left,right)+1; 23 } 24 return -1; 25 } 26 bool isBalanced(TreeNode* root) { 27 return isDepth(root)!=-1; 28 } 29 };