Day: October 27, 2015

Balanced Binary Tree

Posted on

Problem:

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Solution:

Screen Shot 2015-10-27 at 2.36.51 PM

Through each part of the solution, use recursion. Every node acts just like root. Be clear about the balanced conditions:

  1. Both left and right child nodes are balanced
  2. The height difference between the child nodes <= 1

So write another helper function to count the height. Use the same recursion idea to count the height for any node. For any node, the total height = larger child node height + 1.

Nim Game

Posted on

Problem:

You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.

Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.

For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.

Solution:

Coding part is easy. Just justify whether n is one integer multiples of 4.

return n % 4 != 0;

According to the problem’s prototypes, when n = 1, 2, 3, the first goer can definitely win; when n = 4, the first goer will lose. Think about why first goer with 4 stones will definitely lose. Because players are free minded, the second goer can adjust the move following the first one. He will try everything to leave 4 stones to the first goer. So any multiples of 4 equals to n = 4 case.