首页 > 代码库 > Balanced Binary Tree

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. 空树是一颗平衡二叉树

2. 它的左子树和右子树的高度差不超过1

3. 它的左子树和右子树也是平衡二叉树

故判断这棵树是否是平衡二叉树,不仅要求树的高度,也要判断左右子树是否均为平衡二叉树,使用树的后序遍历,求树高度的时候同时判断这棵树是否是平衡二叉书,代码如下:

 1 /** 2  * Definition for binary tree 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     bool isBalanced(TreeNode *root) {13         return getdepth(root) > -1;14     }15     16     int getdepth(TreeNode* root) {  //返回正常高度,说明是平衡二叉树,否则返回-117         if( !root ) return 0;   //空树是平衡二叉树,返回018         int leftdepth = getdepth(root->left);   //左子树高度19         int rightdepth = getdepth(root->right); //右子树高度20         //左子树不是  或  右子树不是   或   左右子树高度差超过121         if( leftdepth == -1 || rightdepth == -1 || abs(leftdepth-rightdepth) > 1 ) return -1;22         return max(leftdepth, rightdepth)+1;23     }24 };

 

Balanced Binary Tree