val) { array_push($ans, $node->val); } if ($node->left) { array_push($queue, $node->left); } if ($node->right) { array_push($queue, $node->right); } } } } return $ans; } public static function rightSideView2(?TreeNode $root): array { if (!$root) { return []; } $ans = []; self::dfs($root, 0, $ans); return $ans; } private static function dfs(?TreeNode $node, int $depth, array & $ans): void { if ($node instanceof TreeNode && $node->val) { if ($depth + 1 > count($ans)) { array_push($ans, 0); } $ans[$depth] = $node->val; self::dfs($node->left, $depth + 1, $ans); self::dfs($node->right, $depth + 1, $ans); } } }