Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Given the root
of a binary tree, return its maximum depth.
A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 3
Example 2:
Input: root = [1,null,2]
Output: 2
Constraints:
[0, 104]
.-100 <= Node.val <= 100
class Solution {
public int maxDepth(TreeNode root) {
// Base Condition
if(root == null) return 0;
// Hypothesis
int left = maxDepth(root.left);
int right = maxDepth(root.right);
// Induction
return Math.max(left, right) + 1;
}
}
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL) return 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return max(left, right) + 1;
}
};
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
depth = 0
level = [root] if root else []
while level:
depth += 1
queue = []
for el in level:
if el.left:
queue.append(el.left)
if el.right:
queue.append(el.right)
level = queue
return depth
In our experience, we suggest you solve this Maximum Depth of Binary Tree LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Maximum Depth of Binary Tree LeetCode Solution
I hope this Maximum Depth of Binary Tree LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>