摘要:
Given a binary tree, return thezigzag level ordertraversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).For example:Given binary tree{3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7return its zigzag level order traversal as:[ [3], ... 阅读全文
摘要:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.Solution: 1 TreeNode *sortedListToBST(ListNode *head) { 2 if(head == NULL) 3 return NULL; 4 if(head->next == NULL) 5 return new TreeNode(head->val)... 阅读全文
摘要:
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 ofeverynode never differ by more than 1.Solution: 1 bool helperBalanced(int *depth, TreeNode * root){ 2 if(root->left... 阅读全文
摘要:
Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.Summary: BFS or DFS with recursion. 1 int minDepth(TreeNode *root) { 2 if(root == NULL) 3 return 0; 4 if(root-... 阅读全文
摘要:
Given an array withnobjects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.Note:You are not suppose to use the l 阅读全文
摘要:
Follow up for "Remove Duplicates":What if duplicates are allowed at mosttwice?For example,Given sorted array A =[1,1,1,2,2,3],Your function should return length =5, and A is now[1,1,2,2,3].Solution: 1 int removeDuplicates(int A[], int n) { 2 if(n = 2){17 //remove A[i]18 ... 阅读全文
摘要:
Given a binary tree, flatten it to a linked list in-place.For example,Given 1 / \ 2 5 / \ \ 3 4 6The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6click to show hints.Hints:If y... 阅读全文
摘要:
Say you have an array for which theithelement is the price of a given stock on dayi.Design an algorithm to find the maximum profit. You may complete at mosttwotransactions.Note:You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).Solution: D 阅读全文