Interview questions · Microsoft
Solve binary-tree reverse printing and LPS
This question evaluates proficiency with tree data structures and level-order traversal semantics for reverse level printing, as well as string algorithmic reasoning and dynamic programming concepts for computing the longest palindromic subsequence, categorized under Coding & Algorithms.
You are given a binary tree node definition:
TreeNode { int val; TreeNode left; TreeNode right; }
Answer the following two algorithmic questions.
1) Reverse-print a binary tree
Implement a function that returns the values of the tree level by level from bottom to top.
- Input:
root(possiblynull) - Output: a list of levels, where each level is a list of node values
- Order requirement: within each level, nodes are listed from left to right, but the levels are returned in reverse (deepest level first).
Example
Tree:
1- left:
2(children:4,5) - right:
3(right child:6)
- left:
Output: [[4,5,6],[2,3],[1]]
2) Longest palindromic subsequence (LPS)
Given a string s, return the length of the longest subsequence of s that is a palindrome.
- A subsequence keeps relative order but may delete characters.
- Input: string
s - Output: integer length
Example
- Input:
"bbbab" - Output:
4(one LPS is"bbbb")
Constraints (assume typical interview constraints)
0 <= number_of_nodes <= 10^5for the tree1 <= |s| <= 2000for LPS
Community answers
Nothing here yet.
Join in on CSWork →