方法一:使用递归的方法,使用一个变量记录以当前节点的左右节点为根节点的子树是否是平衡树,同时根据树的深度判断当前树是否为平衡树。
/** * 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: bool isBalanced(TreeNode* root) { return height(root) >= 0; } int height(TreeNode *root) { if(!root) return 0; int lt = height(root->left); int rt = height(root->right); if(lt == -1 || rt == -1 || abs(lt-rt) > 1) return -1; return max(lt, rt) + 1; } };
原文:http://www.cnblogs.com/chengyuz/p/6714583.html