Posts

Showing posts with the label recursion

649. Binary Tree Upside Down

Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root. Have you met this question in a real interview?    Yes Problem Correction Example Example1 Given a binary tree  {1,2,3,4,5} 1 / \ 2 3 / \ 4 5 return the root of the binary tree  {4,5,2,#,#,3,1} . 4 / \ 5 2 / \ 3 1 Example2 Given a binary tree  {1,2,3,4} 1 / \ 2 3 / 4 return the root of the binary tree  {4,#,2,3,1} . 4 \ 2 / \ 3 1 class Solution { public : /** * @param root: the root of binary tree * @return: new root */ TreeNode * upsideDownBinaryTree (TreeNode * root) { // write your code here //典型的recursion啊,但不太好想 if (root == NULL || (root-...

879. Output Contest Matches

Description 中文 English 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. The  n  is in range  [2, 2^12] . We ensure that the input  n  can be converted into the form  2^k , w...