110. 平衡二叉树
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
Solution(递归版):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { public: bool isBalanced(TreeNode* root) { if(!root) return true; if(std::abs(depth(root->left)-depth(root->right)) > 1 ){ return false; }else{ return isBalanced(root->left) && isBalanced(root->right); } }
int depth(TreeNode* root) { if(!root) return 0; return 1 + std::max(depth(root->left),depth(root->right)); } };
|
思路:
依次向下判断每一个节点的下左右子树的高度差。如果大于1,返回false,否则继续向下判断。