That's a very simple explanation bro. Keep up the good work. To print the left side view: 1. Append the first element value in the tree to the result array before looping. 2. Pop the first element in the loop. def left_view(root): lv = []; q = [root] if(root == None): return [] while q: lv.append(q[0].value) for _ in range(len(q)): node = q.pop(0); if(node.left): q.append(node.left) if(node.right): q.append(node.right) return lv
@indiccoderАй бұрын
Yes bro, perfect logic! 😁
@indiccoderАй бұрын
Python Solution: class Solution: def rightSideView(self, root: Optional[TreeNode]) -> List[int]: # Edge Case - Tree is empty if root == None: return [] # Init rv to empty and q to root node rv = [] q = [root] while q: # Append last node value to right view rv.append(q[-1].val) # For each node in current level add children to q for _ in range(len(q)): node = q.pop(0) if node.left: q.append(node.left) if node.right: q.append(node.right) # Return the Right Side View List return rv
@indiccoderАй бұрын
Java Solution: class Solution { public List rightSideView(TreeNode root) { // Initialize right view list rv to empty list ArrayList rv = new ArrayList(); // If tree is empty, return empty rv list if (root == null) { return rv; } // Initialize queue with root node ArrayList q = new ArrayList(); q.add(root); // BFS while (!q.isEmpty()) { // Add the value of the last node in the queue to rv rv.add(q.get(q.size() - 1).val); // Process each node in the current level int size = q.size(); for (int i = 0; i < size; i++) { // Remove the node from the front of the queue TreeNode node = q.remove(0); // Add its children to the back of the queue if (node.left != null) { q.add(node.left); } if (node.right != null) { q.add(node.right); } } } return rv; } }