Another recursion problem.
class Solution { public: int getHeight(TreeNode *p) { if (!p) return 0; int hL = 1; if (p->left) hL = 1 + getHeight(p->left); int hR = 1; if (p->right) hR = 1 + getHeight(p->right); return (hL > hR ? hL : hR); } bool isBalanced(TreeNode *root) { if (!root || (!root->left && !root->right)) return true; bool bLeft = isBalanced(root->left); if (!bLeft) return false; bool bRight = isBalanced(root->right); if (!bRight) return false; { int hL = getHeight(root->left); int hR = getHeight(root->right); if (abs(hL - hR) < 2) return true; } return false; } };
LeetCode "Balanced Binary Tree",布布扣,bubuko.com
LeetCode "Balanced Binary Tree"
原文地址:http://www.cnblogs.com/tonix/p/3857681.html