NANDURI KARTHIKEYA KRISHNA SAI
VU21CSEN0101813
ADVANCE
CODING-2
NANDURI
KARTHIKEYA KRISHNA SAI
VU21CSEN0101813
Question 1
Given the root of a binary tree, flatten the tree into a
"linked list": The "linked list" should use the same
TreeNode class where the right child pointer points to
the next node in the list and the left child pointer is
always null. The "linked list" should be in the same
order as a pre-order traversal of the binary tree.
Example 1:
Input: root = [1,2,5,3,4,null,6]
Output: [1,null,2,null,3,null,4,null,5,null,6]
Example 2:
Input: root = []
Output: []
Example 3:
NANDURI KARTHIKEYA KRISHNA SAI
VU21CSEN0101813
Input: root = [0]
Output: [0]
Constraints:
The number of nodes in the tree is in the range [0, 2000].
-100 <= Node.val <= 10
Answer:
class Solution {
public void flatten(TreeNode root) {
if (root == null)
return;
flatten(root.left);
flatten(root.right);
TreeNode left = root.left; // flattened left
TreeNode right = root.right; // flattened right
root.left = null;
root.right = left;
// Connect the original right subtree to the end of the new right subtree.
TreeNode rightmost = root;
while (rightmost.right != null)
rightmost = rightmost.right;
rightmost.right = right;
}
NANDURI KARTHIKEYA KRISHNA SAI
VU21CSEN0101813
Submission result
Test case:
NANDURI KARTHIKEYA KRISHNA SAI
VU21CSEN0101813
Test case 2:
Test case 3:
NANDURI KARTHIKEYA KRISHNA SAI
VU21CSEN0101813
Question 2
Given n non-negative integers representing an
elevation map where the width of each bar is 1,
compute how much water it can trap after raining.
Example 2:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array
[0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are
being trapped.
Example 2:
Input: height = [4,2,0,3,2,5]
Output: 9
Constraints:
NANDURI KARTHIKEYA KRISHNA SAI
VU21CSEN0101813
n == height.length
1 <= n <= 2 * 104
0 <= height[i] <= 105
Answer:
public class Solution {
public int trap(int[] height) {
int n = height.length;
int[] maxLeft = new int[n];
int[] maxRight = new int[n];
int lWall = 0, rWall = 0;
for (int i = 0; i < n; i++) {
int j = n - i - 1;
maxLeft[i] = lWall;
maxRight[j] = rWall;
lWall = Math.max(lWall, height[i]);
rWall = Math.max(rWall, height[j]);
int sum = 0;
for (int i = 0; i < n; i++) {
int pot = Math.min(maxLeft[i], maxRight[i]);
sum += Math.max(0, pot - height[i]);
return sum;
}
NANDURI KARTHIKEYA KRISHNA SAI
VU21CSEN0101813
Submission result:
Test case1:
NANDURI KARTHIKEYA KRISHNA SAI
VU21CSEN0101813
Test case 2: