Monday, September 29, 2014

Integer to Roman

Problem

Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.

Idea

定义好radix和symbol很重要

Solution


Populating Next Right Pointers in Each Node

Problem

Too long. Check the 传送们:

Idea


  • 完全binary tree节点数n和层数h的关系
  • n = 2^(h)-1;     (h从1开始)
  • 先把每一层的最右边的next = NULL设置好,然后遍历每一层,起点是每层最左边的点,遍历每个点,把这个点下面的左孩子和右孩子连起来,然后再遍历一次,把不是同一个parent的两个相邻点连起来


  • Solution



    Binary Tree Inorder Traversal

    Problem

    Given a binary tree, return the inorder traversal of its nodes' values.

    For example:

    Idea

    Use stack. Push left child to stack &nbsp > &nbsp push_back(parent->val) to result &nbsp > &nbsp push right child to stack.

    Solution


    Binary Tree Level Order Traversal II

    Problem

    Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

    For example:

    Idea

    做法与binary tree level order traversal 类似。不同的地方是别忘记把结果倒过来.

    Solution


    Sunday, September 28, 2014

    Binary Tree Preorder Traversal

    Problem

    Given a binary tree, return the preorder traversal of its nodes' values.

    For example:
    Given binary tree {1,#,2,3},
      1
       \
        2
       /
      3
    return [1,2,3].

    Idea

    stack 实现根 左 右。

    Solution


    Saturday, September 27, 2014

    Best Time to Buy and Sell Stock 3

    Problem

    Say you have an array for which the ith element is the price of a given stock on day i.
    Design an algorithm to find the maximum profit. You may complete at most two transactions.

    Note:
    You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

    Idea


    Solution


    Binary Tree Level Order Traversal

    Problem

    Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

    Idea

    BFS can solve this problem.

    Note

  • C++ queue
  • Solution