KatInterview

Binary Tree Lateral Perspective and Zero-Sum Triplet Extraction

Trees & GraphsModel answer
EasyModel answerTrees & Graphsbinary-treebfstwo-pointers

Last updated

Solve two fundamental interview tasks: identifying the rightmost nodes of a binary tree by level and finding non-duplicate zero-sum triplets in an un-ordered array.

This multi-part problem tests tree traversal methods and pointer manipulation on sorted arrays.


Task 1: Right-Side Binary Tree Silhouette

Given the root node of a binary tree, list the node values that are visible when viewing the tree from its right flank. Construct the output starting from the top layer to the deepest level.

Example

Input Tree:
       10
      /  \
     20   30
       \    \
        50   40

Output: [10, 30, 40]

Limits

  • Tree size is between 0 and 10,000 nodes.
  • Values of nodes fall within standard 32-bit integer limits.

Task 2: Non-Duplicate Zero-Sum Triplets

Given an integer array values, find all unique triplets [a, b, c] contained in the array such that a + b + c = 0.

The result set must contain no duplicate triplets (e.g., [ -1, 0, 1 ] and [ 0, 1, -1 ] are considered identical). The output ordering of triplets and internal values does not matter.

Example

Input: values = [-1, 0, 1, 2, -1, -4]
Output: [[-1, -1, 2], [-1, 0, 1]]

Limits

  • 3 <= values.length <= 3000
  • -10^5 <= values[i] <= 10^5

Hints

Hint 1

For Task 1: A simple right-branch traversal will fail if a left subtree goes deeper than the right subtree. Think level by level.

Hint 2

For Task 2: Sorting the input array converts the problem into a fixed element plus a two-pointer search.

Hint 3

To avoid duplicate triplets in Task 2 without using a hash set, advance your pointers past equal consecutive values.