Grokking Data Structures & Algorithms for Coding Interviews
0% completed
Solution: Binary Tree Right Side View
Problem Statement
Return the values of the nodes visible from the right of a binary tree, top down. A node is visible when it is the rightmost node on its level.
Examples
Example 1
- Input: root =
[1, 2, 3, null, 5, null, 4] - Expected Output:
[1, 3, 4]
Example 2
- Input: root =
[1, null, 3] - Expected Output:
[1, 3]
Example 3
- Input: root =
[1, 2, 3, 4, null, null, null, 5] - Expected Output:
[1, 3, 4, 5]
Reading the question properly
The word right in the title is misleading, and the third example is there to prove it
.....
.....
.....
Like the course? Get enrolled and start learning!
Sajid Khan
· 3 days ago
// I was able to solve it using preorder traversal, but I swapped the traversal order of the left and right subtrees class Solution { rightSideView(root) { const result = []; this.preOrderTraverse(root, result, 0) return result; } preOrderTraverse(root, result, index) { if (root === null) return; if (result.length === index) result.push(root.val); this.preOrderTraverse(root.right, result, index + 1) this.preOrderTraverse(root.left, result, index + 1) } }
Show 1 reply
Reading Progress
0%