6/21/2020

[LeetCode] 104. Maximum Depth of Binary Tree

Problem : https://leetcode.com/problems/maximum-depth-of-binary-tree/

Calculate depth recursively.


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if root:
            return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
        
        return 0
A iterative solution:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        result = 0
        stack = [(1, root)] if root else []
        
        while stack:
            level, node = stack.pop()
            
            if not node.left and not node.right:
                result = max(result, level)
            else:
                if node.right:
                    stack.append(((level + 1), node.right))
                if node.left:
                    stack.append(((level + 1, node.left)))
        
        return result

Edited on 04/24/2021. Add the iterative solution.

No comments:

Post a Comment