LeetCode Weekly Contest 24
[2017-03-19]
Diameter of Binary Tree
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
##code
For every node, length of longest path which pass it = MaxDepth of its left subtree + MaxDepth of its right subtree.
Convert BST to Greater Tree
Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.
Example:
code
BST中序遍历为升序的,因为先左子树然后中间节点,然后右子树,
这里先右子树然后中间然后左子树,累加右边的即可。
01 Matrix
Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
Example 1:
Input:
Output:
Example 2:
Input:
Output:
Note:
- The number of elements of the given matrix will not exceed 10,000.
- There are at least one 0 in the given matrix.
- The cells are adjacent in only four directions: up, down, left and right.
code
|
|
Output Contest Matches
During the NBA playoffs, we always arrange the rather strong team to play with the rather weak team, like make the rank 1 team play with the rank nth team, which is a good strategy to make the contest more interesting. Now, you’re given n teams, you need to output their final contest matches in the form of a string.
The n teams are given in the form of positive integers from 1 to n, which represents their initial rank. (Rank 1 is the strongest team and Rank n is the weakest team.) We’ll use parentheses(‘(‘, ‘)’) and commas(‘,’) to represent the contest team pairing - parentheses(‘(‘ , ‘)’) for pairing and commas(‘,’) for partition. During the pairing process in each round, you always need to follow the strategy of making the rather strong one pair with the rather weak one.
Example 1:
Example 2:
Example 3:
Note:
- The n is in range [2, $2^{12}$].
- We ensure that the input n can be converted into the form $2^k$, where k is a positive integer.
code
要实现最强的队伍跟最弱的队伍匹配,就是要讲1~n顺序排列,然后第一队跟倒数第一队匹配,构成一个”(1,n)”,将这个字符串放入另一个链表里,然后将第二队跟倒数第二队匹配,构成”(2,n-1)”,并加入链表里。第一个链表处理完后,递归处理新生成的链表,直到新的链表里字符串的数量为1.