3313. Find the Last Marked Nodes in Tree
Explanation:
To solve this problem, we can perform a depth-first search (DFS) traversal of the tree while keeping track of the marked nodes. We need to find the last marked nodes in each branch starting from the root. We can achieve this by passing the marked nodes information as we traverse the tree recursively.
Algorithm:
- Implement a recursive DFS function that takes the current node, a list of marked nodes encountered so far, and a list of last marked nodes encountered in each branch.
- In each recursive call, add the current node to the marked nodes list if it is marked.
- Check if the current node is a leaf node. If yes, add it to the last marked nodes list if it is marked.
- Recursively call the function on the left and right child nodes with updated marked nodes list.
- Finally, return the list of last marked nodes encountered in each branch.
Time Complexity:
The time complexity of this solution is O(N), where N is the number of nodes in the tree. We visit each node only once during the DFS traversal.
Space Complexity:
The space complexity of this solution is O(N) due to the recursive calls and the marked nodes list.
: :
class TreeNode {
int val;
TreeNode left, right;
boolean isMarked;
public TreeNode(int val) {
this.val = val;
}
}
class Solution {
public List<TreeNode> findLastMarkedNodes(TreeNode root) {
List<TreeNode> lastMarkedNodes = new ArrayList<>();
dfs(root, new ArrayList<>(), lastMarkedNodes);
return lastMarkedNodes;
}
private void dfs(TreeNode node, List<TreeNode> markedNodes, List<TreeNode> lastMarkedNodes) {
if (node == null) return;
if (node.isMarked) {
markedNodes.add(node);
}
if (node.left == null && node.right == null) {
if (!markedNodes.isEmpty()) {
lastMarkedNodes.add(markedNodes.get(markedNodes.size() - 1));
}
}
dfs(node.left, new ArrayList<>(markedNodes), lastMarkedNodes);
dfs(node.right, new ArrayList<>(markedNodes), lastMarkedNodes);
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.