Thursday, September 25, 2014

[Leetcode] Flatten Binary Tree to Linked List

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
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.

Analysis:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:

    void helper(TreeNode *root, TreeNode*& lastVisited) {
        if (root == NULL)
            return;
        //preorder, the root->right will be overrided when calling helper(root->left, lastVisited)
        //need to be saved
        TreeNode* right = root->right;
            
        if (lastVisited != NULL)
        {
            lastVisited->left = NULL;
            lastVisited->right = root;
        }
        //remember last visited
        lastVisited = root;
        
        helper(root->left, lastVisited);
        helper(right, lastVisited);
    }

    void flatten(TreeNode *root) {
        TreeNode* lastVisited = NULL;
        helper(root, lastVisited);
    }
};

[Leetcode] Populating Next Right Pointers in Each Node

iven a binary tree
    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Note:
  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
         1
       /  \
      2    3
     / \  / \
    4  5  6  7
After calling your function, the tree should look like:
         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \  / \
    4->5->6->7 -> NULL
Analysis:

/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
class Solution {
public:
    void connect(TreeLinkNode *root) {
        if (root == NULL || (root->left == NULL && root->right == NULL))
            return;
        root->left->next = root->right;
        if (root->next != NULL)
            root->right->next = root->next->left;
        
        connect(root->right);
        connect(root->left);
        
    }
};

[Leetcode] Pascal's Triangle

Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
Analysis:

class Solution {
public:
    vector<vector<int> > generate(int numRows) {
        vector<vector<int> > ret;
        for(int i=0; i<numRows; i++)
        {
            vector<int> row;
            for(int j=0; j<=i; j++)
            {
                //first and last one is 1, others are the sum of current and last pos of last line
                if (j == 0 || j == i)
                    row.push_back(1);
                else
                    row.push_back(ret[i-1][j] + ret[i-1][j-1]);
            }
            ret.push_back(row);
        }
        return ret;
    }
};

[Leetcode] Pascal's Triangle II

Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?

Analysis:

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> ret(rowIndex+1, 1);
        for(int i=0; i<=rowIndex; i++)
        {
            int last  = 1;
            for(int j=0; j<=i; j++)
            {
                if (j == 0 || j == i)
                    ret[j] = 1;
                else
                {
                    //remember the current value before it is overrided
                    int tmp = ret[j];
                    ret[j] += last;
                    last = tmp;
                }
            }
        }
        
        return ret;
    }
};

[Leetcode] Triangle

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.

Analysis:

class Solution {
public:
    int minimumTotal(vector<vector<int> > &triangle) {
        vector<int> ret(triangle.back().size() + 1, 0);
        for(int i=triangle.size()-1; i>=0; i--)
        {
            for(int j = 0; j < triangle[i].size(); j++)
            {
                ret[j] = min(ret[j], ret[j+1]) + triangle[i][j]; 
            }
        }
        
        return ret[0];
    }
};

[Leetcode] Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
       1
      / \
     2   3
Return 6.


Analysis:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:

    int helper(TreeNode* root, int& maxSum)
    {
        if (root == NULL)
            return 0;
        else
        {
            int leftSum = helper(root->left, maxSum);
            int rightSum = helper(root->right,maxSum);
            
            int sum = root->val;
            if (leftSum > 0)
                sum += leftSum;
            if (rightSum > 0)
                sum += rightSum;
            
            maxSum = max(maxSum, sum);
            
            return max(leftSum, rightSum) > 0 ? max(leftSum, rightSum) + root->val : root->val;
        }
    }

    int maxPathSum(TreeNode *root) {
        int sum = INT_MIN;
        helper(root, sum);
        
        return sum;
    }
};

[Leetcode] Valid Palindrome

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.

Analysis:

class Solution {
public:

    bool isAlphanumeric(char c)
    {
        if ((c >= 'a' && c <='z') ||
            (c >= 'A' && c <= 'Z') ||
            (c >= '0' && c <= '9'))
            return true;
        return false;
    }

    bool isPalindrome(string s) {
        int i=0;
        int j = s.size() - 1;
        while(i < j)
        {
            if (!isAlphanumeric(s[i]))
            {
                i++;
                continue;
            }

            if (!isAlphanumeric(s[j]))
            {
                j--;
                continue;
            }

            if (toupper(s[i]) != toupper(s[j]))
                return false;
            
            i++;
            j--;
        }
        
        return true;
    }
};