Created
December 12, 2023 19:37
-
-
Save optimistiks/103a1f27847948d7010d0815bbfa8a6c to your computer and use it in GitHub Desktop.
You are given a root of a binary tree that has n number of nodes. You have to return the right-side view in the form of a list. A right-side view of a binary tree is the data of the nodes that are visible when the tree is viewed from the right side.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { TreeNode } from "./ds_v1/BinaryTree.js"; | |
// Definition of a binary tree node | |
// class TreeNode { | |
// constructor(data) { | |
// this.data = data; | |
// this.left = null; | |
// this.right = null; | |
// } | |
// } | |
function rightSideView(root) { | |
const result = []; | |
if (!root) { | |
return result; | |
} | |
// stack for DFS | |
// stack item = tuple [node, level] | |
// start with root node at level 0 | |
const stack = [[root, 0]]; | |
while (stack.length > 0) { | |
const [node, level] = stack.pop(); | |
if (result.length === level) { | |
// if result length is equal to level | |
// it means we need to add this node | |
// for example length === 0, meaning we need to add node from level 0 (root node) | |
result.push(node.data); | |
} | |
// push left first | |
if (node.left) { | |
stack.push([node.left, level + 1]); | |
} | |
// push right second, so when we pop, we pop right first, going DFS into the right subtree first | |
if (node.right) { | |
stack.push([node.right, level + 1]); | |
} | |
// after we went through the right subtree we will start walking through left subtree, | |
// but since our result array is already filled with values, we won't be adding any values from levels we've visited | |
// we will only add more values on levels that were not present in the initial right subtree | |
} | |
// Replace this placeholder return statement with your code | |
return result; | |
} | |
export { rightSideView }; | |
// tc: O(n) | |
// sc: O(h |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment