Created
November 8, 2015 23:30
-
-
Save goldsborough/1b13eac497fb6b962104 to your computer and use it in GitHub Desktop.
Check is a binary tree is balanced.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template<typename T> | |
std::pair<bool, std::size_t> _tree_is_balanced(const TreeNode<T>* node) | |
{ | |
if (! node) return {true, 0}; | |
auto left = _tree_is_balanced(node->left); | |
if (! left.first) return {false, 0}; | |
auto right = _tree_is_balanced(node->right); | |
if (! right.first) return {false, 0}; | |
if (std::abs<std::size_t>(left.second - right.second) > 1) | |
{ | |
return {false, 0}; | |
} | |
else return {true, left.second + 1 + right.second}; | |
} | |
template<typename T> | |
bool tree_is_balanced(const TreeNode<T>* root) | |
{ | |
return _tree_is_balanced(root).first; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment