Skip to main content

Posts

Showing posts with the label LeetCode Solutions

[LeetCode Solution 54] Spiral Matrix

Question: Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. For example, Given the following matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] You should return  [1,2,3,6,9,8,7,4,5] . Answers: ************************************************************* Approach #1 Using Assitant Matrix Intuition This method is straight forward, we are using an assistant matrix to help us to record the visiting information, i.e. when we meet the board or the element in the matrix has been visited, we have to change the direction. Algorithm Here are some comments before going into the strategy: 1. we can visit all the elements in matrix[m,n] in m*n steps, so the loop is m*n and time complexity is $O(m*n)$ 2. there are 4 directions, right ->down -> left -> up and the back to the right, the order of the direction will not change. which means after going right and we have to change directio

[LeetCode Solution 145] Binary Tree Postorder Traversal

[LeetCode Solution 145]: Binary Tree Postorder Traversal Question: Given a binary tree, return the  postorder  traversal of its nodes' values. For example: Given binary tree  {1,#,2,3} , 1 \ 2 / 3 return  [3,2,1] . Approach #1 Recursive [Accepted] Detail Explanation The first method to solve this problem is using recursive. This is the classical method and straightforward. we can define a helper function to implement recursion. The java code is as follows: Java public class Solution { public List<Integer> postorderTraversal (TreeNode root) { List<Integer> res = new ArrayList<>(); helper(root, res); return res; } public void helper (TreeNode root, List<Integer> res) { if (root != null ) { if (root.left != null ) { helper(root.left, res); } if (root.right != null ) { helper(root.right, res); } res.add(root.val); } } } Complexity Analysis Time complexity :