[LeetCode] 110. Balanced Binary Tree
2017-06-27 19:59
417 查看
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.
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.
class Solution { public: bool isBalanced(TreeNode* root) { return __isBalanced(root).first; } private: pair<bool, int> __isBalanced(TreeNode *root) { if (root == nullptr) return {true, 0}; auto lh = __isBalanced(root->left); if (lh.first == false) return {false, -1}; auto rh = __isBalanced(root->right); if (rh.first == false) return {false, -1}; if (abs(lh.second - rh.second) > 1) { return {false, -1}; } return {true, max(lh.second, rh.second) + 1}; } };
// Optimized class Solution { public: bool isBalanced(TreeNode* root) { return __isBalanced(root) != -1; } private: int __isBalanced(TreeNode *root) { if (root == nullptr) return 0; int lh = __isBalanced(root->left); if (lh == -1) return -1; int rh = __isBalanced(root->right); if (rh == -1) return -1; if (abs(lh - rh) > 1) return -1; return max(lh, rh) + 1; } };
相关文章推荐
- LeetCode 110. Balanced Binary Tree
- leetcode 110. Balanced Binary Tree
- [leetcode] 110. Balanced Binary Tree
- 二叉树递归问题 leetcode 572. Subtree of Another Tree & leetcode 110. Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree
- [LeetCode]110.Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree
- leetcode 110. Balanced Binary Tree
- 【Leetcode】110. Balanced Binary Tree
- 【平衡二叉树】leetcode 110. Balanced Binary Tree
- LeetCode_110.Balanced Binary Tree_平衡二叉树
- LeetCode 110. Balanced Binary Tree
- leetcode 110. Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree
- leetcode-110. Balanced Binary Tree
- LeetCode110. Balanced Binary Tree
- leetCode 110. Balanced Binary Tree 平衡二叉树
- [leetcode: Python] 110. Balanced Binary Tree
- LeetCode --- 110. Balanced Binary Tree
- leetcode 110. Balanced Binary Tree