Delete nodes in linked list and binary tree
TikTokSoftware Engineer · Technical ScreenLast updated
This question evaluates proficiency in mutable data structure operations, specifically linked list node removal and binary tree node replacement/deletion, requiring knowledge of traversal, pointer/reference manipulation, and edge-case handling.
You are asked to solve two short coding tasks. You may assume standard node definitions:
- Singly linked list node:
val,next - Binary tree node:
val,left,right
Task A — Remove the Nth node from the end of a linked list
Given the head of a singly linked list and an integer n, remove the n-th node from the end of the list and return the new head.
Requirements
1 <= n <= length(list)- Aim for
O(L)time whereLis the list length, andO(1)extra space.
Task B — Delete a node from a binary tree and reconnect
Given the root of a binary tree (not necessarily a BST) and an integer key, delete one node whose value equals key and return the (possibly new) root.
To keep the tree structure valid after deletion, perform deletion using this rule:
- Find the node
Xwith valuekey. - Find the deepest, rightmost node in the tree
D. - Replace
X.valwithD.val. - Delete node
Dfrom its parent by setting the corresponding child pointer tonull.
Edge cases
- If
keyis not found, return the original root. - If the tree has only one node and it matches
key, returnnull.
Complexity target: O(N) time, O(N) space is acceptable (e.g., BFS queue), where N is the number of nodes.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.