Skip to main content

Maximum Depth of Binary Tree - Leetcode 104 - Python 3 Easy Ways [Recursion, BFS, DFS]

Maximum Depth of Binary Tree  


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.


Recusive DFS

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        return 1 + max(self.maxDepth(root.left),self.maxDepth(root.right))

BFS

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        lvl = 0
        q = deque([root])
        while q:
            for i in range(len(q)):
                node = q.popleft()
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            lvl += 1
        return lvl

Iterative DFS

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        s = [[root,1]] #stack
        ans = 0
        
        while s:
            n, d = s.pop()
            
            if n:
                ans = max(ans, d)
                s.append([n.left, d+1])
                s.append([n.right, d+1])
                
        return ans


Explaination :



Comments

Popular posts from this blog

May-6 2020 Challenge

  6.   Majority Element Given an array of size  n , find the majority element. The majority element is the element that appears  more than   ⌊ n/2 ⌋  times. You may assume that the array is non-empty and the majority element always exist in the array. Example 1: Input: [3,2,3] Output: 3 Example 2: Input: [2,2,1,1,1,2,2] Output: 2 Solution in Java  class Solution {     public int majorityElement(int[] num) {         int m = num[0], cnt= 1;     for (int i = 1; i < num.length; i++) {         if (cnt == 0) {             m= num[i];             cnt = 1;         } else if (num[i] == m) {             cnt++;         } else              cnt--;    }      return m;...

Leetcode 424. Longest Repeating Character Replacement. Python (Sliding Window)

  424 .  Longest Repeating Character Replacement You are given a string  s  and an integer  k . You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most  k  times. Return  the length of the longest substring containing the same letter you can get after performing the above operations .   Example 1: Input: s = "ABAB", k = 2 Output: 4 Explanation: Replace the two 'A's with two 'B's or vice versa. Example 2: Input: s = "AABABBA", k = 1 Output: 4 Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA". The substring "BBBB" has the longest repeating letters, which is 4.   Constraints: 1 <= s.length <= 10 5 s  consists of only uppercase English letters. 0 <= k <= s.length Solution :  class Solution: def characterReplacement(self, s: str, k: int) -> int: hm = {} ans = 0 ...

Longest Substring Without Repeating Characters - Leetcode 3 - Python

Given a string s, find the length of the longest substring without repeating characters. class Solution:     def lengthOfLongestSubstring(self, s: str) -> int:         charSet = set()         left = 0         ans = 0         for right in range(len(s)):             while s[right] in charSet:                 charSet.remove(s[left])                 left+=1             charSet.add(s[right])             ans = max(ans, right-left+1)         return ans                  Explained :