From 7f70ae437bbe7a7f31c1a5e32b702649a7245976 Mon Sep 17 00:00:00 2001 From: mkn-root12 <75845290+mkn-root12@users.noreply.github.com> Date: Sun, 17 Oct 2021 22:27:49 +0530 Subject: [PATCH] Update 104. Maximum Depth of Binary Tree.cpp --- C++/104. Maximum Depth of Binary Tree.cpp | 37 +++++++++++++++-------- 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/C++/104. Maximum Depth of Binary Tree.cpp b/C++/104. Maximum Depth of Binary Tree.cpp index b9fa8e2..91fa648 100644 --- a/C++/104. Maximum Depth of Binary Tree.cpp +++ b/C++/104. Maximum Depth of Binary Tree.cpp @@ -21,18 +21,31 @@ Subscribe to see which companies asked this question class Solution { public: int maxDepth(TreeNode* root) { - if(root == NULL) + + if(root == nullptr) return 0; - if(root->left == NULL && root->right == NULL) - return 1; - if(root->left != NULL && root->right == NULL) - return maxDepth(root->left) + 1; - if(root->right != NULL && root->left == NULL) - return maxDepth(root->right) + 1; - if(root->right != NULL && root->left != NULL) { - int leftdepth = maxDepth(root->left); - int rightdepth = maxDepth(root->right); - return leftdepth > rightdepth ? leftdepth + 1 : rightdepth + 1; + + queue q; + q.push(root); + int depth = 0; + + while(!q.empty()) + { + int count = q.size(); + while(count--) + { + TreeNode* n = q.front(); + q.pop(); + + if(n->left) + q.push(n->left); + if(n->right) + q.push(n->right); + } + + depth++; } + + return depth; } -}; \ No newline at end of file +};