Skip to content

cousins, right side view#1594

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

cousins, right side view#1594
shaikhmisrail wants to merge 1 commit intosuper30admin:masterfrom
shaikhmisrail:master

Conversation

@shaikhmisrail
Copy link
Copy Markdown

No description provided.

@super30admin
Copy link
Copy Markdown
Owner

Right Side View of a tree (leetcode-199.py)

Your solution correctly implements the level-order traversal to capture the rightmost node at each level. The code is efficient with O(n) time and space complexity. However, there are a few points to improve:

  1. Variable Names: While res is a common abbreviation, using result can make the code more readable for others. Similarly, q could be named queue for clarity.

  2. Comments: You have included comments for time and space complexity, which is good. However, consider adding a brief comment explaining the algorithm: "We traverse each level and add the last node's value in the level to the result."

  3. Initialization: You initialize curr = None at the start of the while loop. This is acceptable, but note that the inner for-loop will always run at least once (because the queue is not empty when we enter the while loop), so curr will always be set to a TreeNode. Therefore, the check if curr after the loop is redundant because curr will never be None. You can safely remove that check and directly append curr.val.

  4. Consistency: The code uses deque from collections, but it's not explicitly imported in the provided code snippet. Make sure to include the import statement: from collections import deque.

  5. Edge Cases: Your code handles the empty tree correctly.

Overall, your solution is correct and efficient. With minor improvements in code clarity, it will be excellent.

VERDICT: PASS


Cousins in Tree (leetcode-993.py)

Your approach using BFS is good, and you have the right idea to track the parent and depth. However, there are a few issues to address:

  1. Storing Parent Information: Instead of storing the parent's value (as an integer), you should store the parent node itself. This is more robust and aligns with the problem's requirement (even though values are unique, it is better to compare nodes). You can do this by storing tuples (node, parent) in the queue or by having a separate queue for parents. In your current code, you are storing the value of the parent, which might work because values are unique, but it is not the standard way.

  2. Early Termination: Your code checks for both found at the start of the level and then breaks if only one is found. However, this check should be done after processing the entire level, not during. In the reference solution, after processing all nodes in a level, it checks: if both are found, it returns whether parents are different; if only one is found, it returns false (because they are not at the same depth). Your code does this check at the beginning of the level, which is incorrect because you haven't processed all nodes in the level. You should move these checks to after the inner for-loop (which processes all nodes in the current level).

  3. Initial Check for Root: Your initial check for root value is correct (if x or y is root, return false), but note that the root has no parent. However, your code does not set the parent for the root's children correctly? Actually, in your code, when you process the root, you add its children and set their parent to the root's value. This is correct.

  4. Code Structure: Consider using a tuple or a separate queue to store the parent node. For example, you can do:
    q = deque([(root, None)]) and then when you pop, you get (node, parent). Then when you add children, you add (child, node). This simplifies the code.

  5. Edge Cases: Test with examples where both nodes are children of the same parent (should return false) and where they are cousins (same depth, different parents). Also test when one node is at a deeper level than the other.

Here is a corrected version of your code using tuples:

from collections import deque

class Solution:
    def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
        if root.val == x or root.val == y:
            return False
            
        q = deque()
        q.append((root, None))   # (node, parent)
        x_found = False
        y_found = False
        x_parent = None
        y_parent = None
        
        while q:
            size = len(q)
            for _ in range(size):
                curr, parent = q.popleft()
                if curr.val == x:
                    x_found = True
                    x_parent = parent
                if curr.val == y:
                    y_found = True
                    y_parent = parent
                
                if curr.left:
                    q.append((curr.left, curr))
                if curr.right:
                    q.append((curr.right, curr))
            
            if x_found and y_found:
                return x_parent != y_parent
            if x_found or y_found:
                return False
        return False

This code processes each level completely, then checks at the end of the level. It stores the parent node (not value), which is more accurate.

VERDICT: NEEDS_IMPROVEMENT

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