Leetcode-Flatten Binary Tree to Linked List(Java)

Question:

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

    1
   / \
  2   5
 / \   \
3   4   6

The flattened tree should look like:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

Hint:
If you notice carefully in the flattened tree, each node’s right child points to the next node of a pre-order traversal.

Thinking:

It’s a simple dfs question and it’s pre-order. So we need to make the left-child become right-child of root and make right-child become whole left-child’s right-child.

Solution:

public class Solution {
    public void flatten(TreeNode root) {
        if (root == null)
            return;
        dfs(root);
    }

    public TreeNode dfs(TreeNode root){

        if (root.left == null && root.right == null){
            return root;
        }

        TreeNode left = null;
        TreeNode right = null;
        TreeNode preleft = root.left;
        TreeNode preright = root.right;
        if (preleft == null){
            return dfs(preright);
        }
        else if(preright == null){
            root.left = null;
            root.right = preleft;
            return dfs(preleft);
        }
        else{
            left = dfs(preleft);
            right = dfs(preright);
            root.left = null;
            root.right = preleft;
            left.right = preright;
            return right;
        }
    }
}

Leetcode-Triangle(Java)

Question:

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

For example, given the following triangle:

[
       [2],
     [3,4],
    [6,5,7],
   [4,1,8,3]
]

The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

Thinking:
It’s a simple dynamic programming question. The expression is dp[i][j] = min(d[i-1][j-1], d[i][j]) + triangle[i][j].

But the first time, my code is time exceed:

public class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        int lr = triangle.size();
        if(lr == 0){
            return 0;
        }
        int lc = triangle.get(lr-1).size();
        int min = 100000;
        for(int i = 0; i < lc; i++){
            int tmp = dp(triangle, lr-1, i);
            if(tmp < min)
                min = tmp;
        }
        return min;
    }

    public int dp(List<List<Integer>> triangle, int row, int column){
        if(row == 0){
            return triangle.get(0).get(0);
        }
        int value = triangle.get(row).get(column);
        int size = triangle.get(row-1).size();
        if(column >= size){
            return dp(triangle, row-1, column-1) + value;
        }
        else if(column - 1 < 0){
            return dp(triangle, row-1, column) + value;
        }
        else{
            int res1 = dp(triangle, row-1, column-1) + value;
            int res2 = dp(triangle, row-1, column) + value;
            if(res1 < res2){
                return res1;
            }
            else{
                return res2;
            }
        }
    }
}

Then I noticed the bonus, so I change my mind to use iteration:

public class Solution{
    public int minimumTotal(List<List<Integer>> triangle){
        int lr = triangle.size();
        int[] min = new int[lr];
        int[] tempmin = new int[lr];
        min[0] = triangle.get(0).get(0);
        for(int i = 1; i < lr; i++){
            tempmin[0] = min[0] + triangle.get(i).get(0);
            tempmin[i] = min[i-1] + triangle.get(i).get(i);
            for(int j = 1; j < i; j++){
                int res1 = min[j-1] + triangle.get(i).get(j);
                int res2 = min[j] + triangle.get(i).get(j);
                if(res1 < res2)
                    tempmin[j] = res1;
                else
                    tempmin[j] = res2;
            }
            for(int k = 0; k < i+1; k++){
                min[k] = tempmin[k];
            }
        }
        int m = 100000;
        for(int i = 0; i < lr; i++){
            if(min[i] < m)
                m = min[i];
        }
        return m;
    }
}

HTTP method: get and post

HTTP:

HTTP is the foundation of data commnication of the World Wide Web. The basic work method of http is request and response.

There are two methods of HTTP request: Get and Post.

Get - get request data from specific source.
Post - Push data which will be dealed to specific source.

GET:

Note that the query string (name/value pairs) is sent in the URL of a GET request:

http://www.w3schools.com/tags/ref_httpmethods.asp

Some other notes on GET requests:

GET requests can be cached

GET requests remain in the browser history

GET requests can be bookmarked

GET requests should never be used when dealing with sensitive data

GET requests have length restrictions

GET requests should be used only to retrieve data

POST:

Note that the query string (name/value pairs) is sent in the HTTP message body of a POST request:

POST /test/demo_form.asp HTTP/1.1
Host: w3schools.com
name1=value1&name2=value2

Some other notes on POST requests:

POST requests are never cached

POST requests do not remain in the browser history

POST requests cannot be bookmarked

POST requests have no restrictions on data length

Compare GET vs. POST:

Tables GET POST
BACK button/Reload Harmless Data will be re-submitted
Bookmarked can be bookmarked Can not be bookmarked
Cached Can be cached Can not be cached
History Parameters remain in browser history Parameters are not saved in browser history
Restrictions on data length Yes No
Security Less secure Safer
Visibility Visible Not visible in URL

Reference: http://www.w3schools.com/tags/ref_httpmethods.asp

Leetcode-Construct Binary Tree from Preorder and Inorder Traversal(Java)

Question:

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

Thinking:

This question is similar with Construct Binary Tree from Inorder and Postorder Traversal. We should understand the differences and the sequences of these three methods. And divide into three parts- root, left child and right child.

Solution:

public TreeNode buildTree(int[] preorder, int[] inorder) {
    int l = preorder.length;
    if (l == 0)
        return null;


    return dp(preorder, inorder, 0, l-1, 0, l-1);
    }

    private TreeNode dp(int[] preorder, int[] inorder, int preStart, int preEnd, int inStart, int inEnd){
    if (preStart > preEnd || preEnd >= preorder.length || inEnd >= preorder.length)
        return null;
    TreeNode root = new TreeNode(preorder[preStart]);
    int index = inStart;
    for (; index < inEnd; index++){
        if (inorder[index] == preorder[preStart])
            break;
    }

    TreeNode left = dp(preorder, inorder, preStart+1, preStart+index-inStart, inStart, index-1);
    TreeNode right = dp(preorder, inorder,preStart+index-inStart+1, preEnd, index+1, inEnd);
    root.left = left;
    root.right = right;

    return root;
}    

This method can be improved by using HashMap to make it faster when fiding the index of root.
Reference:http://blog.csdn.net/linhuanmars/article/details/24389549
Code:

static HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
public TreeNode buildTree(int[] preorder, int[] inorder) {
    int l = preorder.length;
    if (l == 0)
        return null;
    for (int i = 0; i < l; i++)
        map.put(inorder[i], i);

    return dp(preorder, inorder, 0, l-1, 0, l-1);
}

private TreeNode dp(int[] preorder, int[] inorder, int preStart, int preEnd, int inStart, int inEnd){
    if (preStart > preEnd || inStart > inEnd)
        return null;
    TreeNode root = new TreeNode(preorder[preStart]);

    int index = map.get(preorder[preStart]);

    TreeNode left = dp(preorder, inorder, preStart+1, preStart+index-inStart, inStart, index-1);
    TreeNode right = dp(preorder, inorder,preStart+index-inStart+1, preEnd, index+1, inEnd);
    root.left = left;
    root.right = right;

    return root;
}

Leetcode-Pow(x, n)(Java)

Question:

Implement pow(x, n).

Thinking:

It’s a simple but not simple question. There are many solutions for this problem. But how can we find the most effienct one. We can use recursion to reduce the times of multipling and check the bound of data to reduce the times of recursions. Finally, the code is below:

static boolean negflag = false;
public double myPow(double x, int n) {
    if (n < 0){
        negflag = true;
        return 1 / dp(x, -n);
    }
    else
        return dp(x, n);

}
private double dp(double x, int n){
    if (n == 0)
        return 1;
    if (n == 1)
        return x;
    if (n == 2)
        return x * x;

    int m = n / 2;
    int k = n % 2;
    double v = dp(x, m);
    if (negflag == true && v > 100000)
        return 100000;
    if (negflag == false && v < 0.00001)
        return 0;

    if (k == 0)
        return v * v;
    else
        return v * v * x;
}

By the way, I have to metion that my python solution is like, lol:

def myPow(self, x, n):
    return x**n