Binary Tree: Postorder Traversal

Tree Node Definition # Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, x: int) -> None: self.val = x self.left = None self.right = None Recursive Implementation left ➡️ right ➡️ root class Solution: def traversal(self, root: 'TreeNode', result=None) -> List[List[int]]: """ 0 / \ 1 2 / \ 3 4 / \ 6 9 Post-order...: [3, 6, 9, 4, 1, 2, 0] T: O(N) S: O(N) worst case; O(log N) average """ if result is None: result = [] if not root: return [] self....

December 12, 2022 · 1 min · 174 words · Me

Binary Tree: Inorder Traversal

Tree Node Definition # Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, x: int) -> None: self.val = x self.left = None self.right = None Recursive Implementation left ➡️ root ➡️ right class Solution: def traversal(self, root: 'TreeNode', result=None) -> List[List[int]]: """ 0 / \ 1 2 / \ 3 4 / \ 6 9 In-order...: [3, 1, 6, 4, 9, 0, 2] T: O(N) S: O(N) worst case; O(log N) average """ if result is None: result = [] if not root: return [] self....

December 12, 2022 · 1 min · 187 words · Me

Binary Tree: Preorder Traversal

Tree Node Definition # Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, x: int) -> None: self.val = x self.left = None self.right = None Recursive Implementation root ➡️ left ➡️ right class Solution: def traversal(self, root: 'TreeNode', ans=None) -> List[List[int]]: """ 0 / \ 1 2 / \ 3 4 / \ 6 9 Pre-order...: [0, 1, 3, 4, 5, 9, 2] """ if not root: return [] if ans is None: ans = [] ans....

December 12, 2022 · 1 min · 151 words · Me

Binary Tree Types

1. Full (Proper) Binary Tree # Each nodes has either 2 or 0 children. 12 8 18 5 11 2. Degenerate (Pathological) Binary Tree # Each internal node has either a right or a left child. # Each node is a left node or each node is a right node. 1 1 2 2 3 3 4. Complete Binary Tree # Each level is filled from left to right. 8 5 3 4 6 7 5....

December 10, 2022 · 2 min · 218 words · Me

Leetcode 104 Maximum Depth of Binary Tree

Problem Statement 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: 3 9 20 15 7 Input: root = [3,9,20,null,null,15,7] Output: 3 Example 2: Input: root = [1,null,2] Output: 2 Key Insights We can Recursive Solution # Definition for a binary tree node....

December 10, 2022 · 2 min · 321 words · Me