Aquí está la solución para la vista lateral derecha del árbol binario donde se intenta resolver el problema a continuación
Input: root = [1,2,3,null,5,null,4] Output: [1,3,4]
Input: root = [1,null,3] Output: [1,3]
Código con comentarios proporcionados a continuación
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) }Las preguntas son: -
if(!root) return; que devuelve exactamentesu respuesta es muy apreciada
Saludos
Carolina