Skip to content

Complete Linked-List-2#1428

Open
PrakarshKamal wants to merge 1 commit intosuper30admin:masterfrom
PrakarshKamal:master
Open

Complete Linked-List-2#1428
PrakarshKamal wants to merge 1 commit intosuper30admin:masterfrom
PrakarshKamal:master

Conversation

@PrakarshKamal
Copy link
Copy Markdown

No description provided.

@super30admin
Copy link
Copy Markdown
Owner

Strengths:

  • Your solution correctly implements the in-order traversal and provides the correct sequence of values.
  • The code is clean and easy to understand.
  • The next() and hasNext() methods are efficient with O(1) time complexity.

Areas for Improvement:

  • The space complexity of your solution is O(n), which is not optimal for this problem. The problem requires O(h) space, meaning you should not store all node values at once.
  • Consider using a stack to traverse the tree incrementally. This way, you only store the leftmost path of the tree at any point, which uses O(h) space.
  • The initialization in your solution does a full traversal upfront, which might be inefficient for large trees if the iterator is only used partially.
  • The reference solution uses a stack to push all left nodes during initialization and then pops them one by one, pushing the right subtree's left nodes when needed. This approach is more memory-efficient for the problem constraints.

To improve, you can modify your solution to use a stack instead of a list. Here's a quick outline:

  • Initialize a stack.
  • In the constructor, push all left nodes starting from the root.
  • For next(), pop the top node, push all left nodes of its right child, and return the value.
  • For hasNext(), check if the stack is empty.

This approach will meet the O(h) space requirement and still maintain O(1) amortized time for next().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants