Balanced Binary Tree
Balanced Binary Tree
Total Accepted: 86508 Total Submissions: 263690 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.
/** * 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 getTreeHeight(TreeNode* root){ if(root==NULL){ return 0; } int lh = getTreeHeight(root->left); int rh = getTreeHeight(root->right); return lh>rh ? lh+1:rh+1; } bool isBalanced(TreeNode* root) { if(root==NULL){ return true; } int lh = getTreeHeight(root->left); int rh = getTreeHeight(root->right); if(fabs(lh-rh)<=1){ return isBalanced(root->left) && isBalanced(root->right); }else{ return false; } } };
Next challenges: (E) Maximum Depth of Binary Tree
写者:zengzy
出处: http://www.cnblogs.com/zengzy
标题有【转】字样的文章从别的地方转过来的,否则为个人学习笔记