LeetCode - Blind 75 - Validate Binary Search Tree
The Problem Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node’s key. The right subtree of a node contains only nodes with keys greater than the node’s key. Both the left and right subtrees must also be binary search trees. A subtree of treeName is a tree consisting of a node in treeName and all of its descendants. ...
LeetCode - Blind 75 - Binary Tree Level Order Traversal
The Problem Given the root of a binary tree, return the level order traversal of its nodes’ values (i.e., from left to right, level by level). Examples Input: root = [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]] Input: root = [1] Output: [[1]] Input: root = [] Output: [] Constraints The number of nodes in the tree is in the range [0, 2000]. -1000 <= Node.val <= 1000 BFS Solution func levelOrder(_ root: TreeNode?) -> [[Int]] { if root == nil { return [] } var queue: [TreeNode?] = [] queue.append(root) var res: [[Int]] = [] while !queue.isEmpty { var level: [Int] = [] for _ in 0 ..< queue.count { let node = queue.removeFirst() if let node = node { level.append(node.val) queue.append(node.left) queue.append(node.right) } } if !level.isEmpty { res.append(level) } } return res } Explanation When you see that a binary tree problem involves level order traversal, it means the solution usually implies the breadth-first search (BFS) algorithm. BFS is a common solution to this problem because, according to Wikipedia, breadth-first search is also called “level-order search.” The core idea behind BFS is to iterate level by level from top to bottom, and from left to right. ...
LeetCode - Blind 75 - Lowest Common Ancestor of a Binary Search Tree
The Problem Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” Examples ...
LeetCode - Blind 75 - Subtree of Another Tree
The Problem Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values as subRoot, and false otherwise. A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node’s descendants. The tree tree could also be considered as a subtree of itself. Examples ...
LeetCode - Blind 75 - Same Tree
The Problem Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same values. Examples Input: p = [1,2,3], q = [1,2,3] Output: true Input: p = [1,2], q = [1,null,2] Output: false ...