Problem Link: http://oj.leetcode.com/problems/surrounded-regions/ We can do follows in the 2D board. Use BFS from all 'O' cells on the boundary and mark all connected 'O' cells Scan the board and flip all unmarked 'O' to 'X'. The following code is py…
Problem Link: http://oj.leetcode.com/problems/interleaving-string/ Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example, Given: s1 = "aabcc", s2 = "dbbca", When s3 = "aadbbcbcac", return t…
Problem link: http://oj.leetcode.com/problems/reverse-words-in-a-string/ Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". LeetCode OJ supports Python now! The s…
Problem Link: https://oj.leetcode.com/problems/validate-binary-search-tree/ We inorder-traverse the tree, and for each node we check if current_node.val > prev_node.val. The code is as follows. # Definition for a binary tree node # class TreeNode: #…
Problem Link: https://oj.leetcode.com/problems/recover-binary-search-tree/ We know that the inorder traversal of a binary search tree should be a sorted array. Therefore, we can compare each node with its previous node in the inorder to find the two…
Problem Link: https://oj.leetcode.com/problems/same-tree/ The following recursive version is accepted but the iterative one is not accepted... # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left =…
Problem Link: https://oj.leetcode.com/problems/symmetric-tree/ To solve the problem, we can traverse the tree level by level. For each level, we construct an array of values of the length 2^depth, and check if this array is symmetric. The tree is sym…
Problem Link: https://oj.leetcode.com/problems/binary-tree-level-order-traversal/ Traverse the tree level by level using BFS method. # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # se…
Problem Link: https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ Just BFS from the root and for each level insert a list of values into the result. # Definition for a binary tree node # class TreeNode: # def __init__(self, x):…
Problem Link: https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/ Simply BFS from root and count the number of levels. The code is as follows. # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x #…