From 5843fa02f742fdb5f2fc4ce3e62dcbadbb521fcd Mon Sep 17 00:00:00 2001 From: Shad Sheikh Date: Fri, 2 Aug 2024 16:41:05 +0530 Subject: [PATCH] Improved 0110-balanced-binary-tree in cpp --- cpp/0110-balanced-binary-tree.cpp | 49 +++++++++++++++++++------------ 1 file changed, 31 insertions(+), 18 deletions(-) diff --git a/cpp/0110-balanced-binary-tree.cpp b/cpp/0110-balanced-binary-tree.cpp index 751c3e21f..590d4249c 100644 --- a/cpp/0110-balanced-binary-tree.cpp +++ b/cpp/0110-balanced-binary-tree.cpp @@ -21,27 +21,40 @@ class Solution { public: bool isBalanced(TreeNode* root) { - int height = 0; - return dfs(root, height); + return dfs(root).first; } + // bool isBalanced(TreeNode* root) { + // int height = 0; + // return dfs(root, height); + // } + private: - bool dfs(TreeNode* root, int& height) { - if (root == NULL) { - height = -1; - return true; - } + pair dfs(TreeNode* root) { + if (!root) return {true, 0}; + + auto left = dfs(root->left); + auto right = dfs(root->right); + + bool balanced = left.first && right.first && abs(left.second - right.second) <= 1; + return {balanced, 1 + max(left.second, right.second)}; + } + // bool dfs(TreeNode* root, int& height) { + // if (root == NULL) { + // height = -1; + // return true; + // } - int left = 0; - int right = 0; + // int left = 0; + // int right = 0; - if (!dfs(root->left, left) || !dfs(root->right, right)) { - return false; - } - if (abs(left - right) > 1) { - return false; - } + // if (!dfs(root->left, left) || !dfs(root->right, right)) { + // return false; + // } + // if (abs(left - right) > 1) { + // return false; + // } - height = 1 + max(left, right); - return true; - } + // height = 1 + max(left, right); + // return true; + // } };