'Node is not Empty then what exactly we return in JavaScript code
Here is soln for Binary Tree Right Side View where trying to solve below problem
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Input: root = [1,null,3]
Output: [1,3]
Code with comments provided below
var rightSideView = function(root) {
const levels = [];
//DFS solutions often allow us to find a concise, recursive solution, and while they're not always the first thought when it comes to tree traversal problems where the level is important, in this case we don't need the level as a whole, we just need one end of each level.
dfs(root, levels)
const res = [];
for(let l of levels){
res.push(l.pop())
}
return res
};
function dfs(root, levels, level = 0){
// Base Case
if(!root) return;
if(!levels[level]){
levels[level] = [];
}
levels[level].push(root.val);
// Recur for left subtree then right subtree
dfs(root.left, levels, level + 1)
dfs(root.right, levels, level + 1)
}
Questions are :-
- The line
if(!root) return;What does it return exactly - Does the comments provided in code are right?
Your response is much appreciated
Regards
Carolyn
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

