判断一棵树是不是平衡二叉树,之前做过,还有点印象,用一个函数返回树的高度,如果是-1的话,就说明子树不平衡。
1A很开心~
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 int height(TreeNode * root) { 13 int hleft, hright; 14 hleft = hright = 0; 15 if (root->left != NULL) { 16 hleft = height(root->left); 17 } 18 if (root->right != NULL) { 19 hright = height(root->right); 20 } 21 if (hleft < 0 || hright < 0 || abs(hleft - hright) > 1) { 22 return -1; 23 } 24 return max(hleft, hright) + 1; 25 } 26 bool isBalanced(TreeNode *root) { 27 if (root == NULL) { 28 return true; 29 } else { 30 return height(root) >= 0; 31 } 32 } 33 };
[Leetcode][Tree][Balanced Binary Tree],布布扣,bubuko.com
[Leetcode][Tree][Balanced Binary Tree]
原文:http://www.cnblogs.com/poemqiong/p/3815396.html