Advancecoding 2
Advancecoding 2
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:
Constraints:
The number of nodes in the tree is in the range [0, 2000].
-100 <= Node.val <= 10
Answer:
class Solution {
if (root == null)
return;
flatten(root.left);
flatten(root.right);
root.left = null;
root.right = left;
// Connect the original right subtree to the end of the new right subtree.
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
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 {
int n = height.length;
int j = n - i - 1;
maxLeft[i] = lWall;
maxRight[j] = rWall;
int sum = 0;
return sum;
}
NANDURI KARTHIKEYA KRISHNA SAI
VU21CSEN0101813
Submission result:
Test case1:
NANDURI KARTHIKEYA KRISHNA SAI
VU21CSEN0101813
Test case 2: