Conversation with Merlin [email protected] · Wed Nov 08 2023

como funciona paso a paso este codigo recursivo, y porque el imprimir no esta fuera del if static void ImprimirNodosDesdeUltimo(Nodo nodo) { if (nodo != null) { ImprimirNodosDesdeUltimo(nodo.Siguiente); Console.WriteLine($"Nombre: {nodo.Nombre}, Edad: {nodo.Edad}"); } }

El código que has compartido es una función recursiva llamada ImprimirNodosDesdeUltimo que toma un parámetro nodo del tipo Nodo.

El funcionamiento detallado paso a paso de esta función recursiva sería el siguiente:

  1. Se pasa un nodo a la función ImprimirNodosDesdeUltimo.
  2. Se verifica si el nodo no es nulo (es decir, si existe un nodo).
  3. Si el nodo no es nulo, se llama a la función ImprimirNodosDesdeUltimo con el siguiente nodo (nodo.Siguiente), lo que significa que la función se llamará a sí misma con el siguiente nodo.
  4. Después de que se complete la llamada recursiva, se imprime en la consola el nombre y la edad del nodo actual.

El motivo por el cual la instrucción Console.WriteLine no está fuera del if es que esta función sigue un enfoque de recorrido en profundidad (depth-first traversal) de una estructura de datos enlazada, y el paso Console.WriteLine se realiza después de que todas las llamadas recursivas hayan terminado de explorar los nodos siguientes.

En resumen, este código imprime de forma recursiva los nombres y edades de los nodos comenzando desde el último nodo en la lista enlazada, debido a la naturaleza de la recursión y el recorrido en profundidad utilizado.

pero si nodo es null ya no entra al if entonces como o porque se imprime

Entiendo la confusión. En el código que has compartido, la instrucción Console.WriteLine está dentro del cuerpo del if que verifica si el nodo no es nulo. Por lo tanto, cuando la función ImprimirNodosDesdeUltimo es llamada con un nodo que es nulo, la condición nodo != null evalúa a falso y la ejecución de la función no entra en el bloque del if, por lo que no se ejecuta la impresión con Console.WriteLine.

En resumen, si el nodo es nulo, la función simplemente termina sin hacer ninguna impresión. Esto es importante para evitar intentar acceder a las propiedades de un objeto nulo, lo que podría resultar en un error en tiempo de ejecución.

Espero que esto aclare tus dudas. Si necesitas más información o alguna otra aclaración, no dudes en preguntar.

Tree created using the Logo programming language and relying heavily on recursion. Each branch can be seen as a smaller version of a tree. Sierpenski triangle being drawn in turtle graphics In computer science, recursion is a method of solving a computational problem where the solution depends on solutions to smaller instances of the same problem.[1][2] Recursion solves such recursive problems by using functions that call themselves from within their own code. The approach can be applied to many types of problems, and recursion is one of the central ideas of computer science.[3] The power of recursion evidently lies in the possibility of defining an infinite set of objects by a finite statement. In the same manner, an infinite number of computations can be described by a finite recursive program, even if this program contains no explicit repetitions.Niklaus Wirth, Algorithms + Data Structures = Programs, 1976[4] Most computer programming languages support recursion by allowing a function to call itself from within its own code. Some functional programming languages (for instance, Clojure)[5] do not define any looping constructs but rely solely on recursion to repeatedly call code. It is proved in computability theory that these recursive-only languages are Turing complete; this means that they are as powerful (they can be used to solve the same problems) as imperative languages based on control structures such as while and for. Repeatedly calling a function from within itself may cause the call stack to have a size equal to the sum of the input sizes of all involved calls. It follows that, for problems that can be solved easily by iteration, recursion is generally less efficient, and, for large problems, it is fundamental to use optimization techniques such as tail call optimization.[citation needed] Recursive functions and algorithms[edit] A common algorithm design tactic is to divide a problem into sub-problems of the same type as the original, solve those sub-problems, and combine the results. This is often referred to as the divide-and-conquer method; when combined with a lookup table that stores the results of previously solved sub-problems (to avoid solving them repeatedly and incurring extra computation time), it can be referred to as dynamic programming or memoization. Base case[edit] A recursive function definition has one or more base cases, meaning input(s) for which the function produces a result trivially (without recurring), and one or more recursive cases, meaning input(s) for which the program recurs (calls itself). For example, the factorial function can be defined recursively by the equations 0! = 1 and, for all n > 0, n! = n(n 1)!. Neither equation by itself constitutes a complete definition; the first is the base case, and the second is the recursive case. Because the base case breaks the chain of recursion, it is sometimes also called the "terminating case". The job of the recursive cases can be seen as breaking down complex inputs into simpler ones. In a properly designed recursive function, with each recursive call, the input problem must be simplified in such a way that eventually the base case must be reached. (Functions that are not intended to terminate under normal circumstancesfor example, some system and server processesare an exception to this.) Neglecting to write a base case, or testing for it incorrectly, can cause an infinite loop. For some functions (such as one that computes the series for e = 1/0! + 1/1! + 1/2! + 1/3! + ...) there is not an obvious base case implied by the input data; for these one may add a parameter (such as the number of terms to be added, in our series example) to provide a 'stopping criterion' that establishes the base case. Such an example is more naturally treated by corecursion,[how?] where successive terms in the output are the partial sums; this can be converted to a recursion by using the indexing parameter to say "compute the nth term (nth partial sum)". Recu

en.wikipedia.org

What is Recursion?The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using a recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc. A recursive function solves a particular problem by calling a copy of itself and solving smaller subproblems of the original problems. Many more recursive calls can be generated as and when required. It is essential to know that we should provide a certain case in order to terminate this recursion process. So we can say that every time the function calls itself with a simpler version of the original problem. Need of Recursion Recursion is an amazing technique with the help of which we can reduce the length of our code and make it easier to read and write. It has certain advantages over the iteration technique which will be discussed later. A task that can be defined with its similar subtask, recursion is one of the best solutions for it. For example; The Factorial of a number. Properties of Recursion: Performing the same operations multiple times with different inputs. In every step, we try smaller inputs to make the problem smaller. Base condition is needed to stop the recursion otherwise infinite loop will occur. Algorithm: Steps The algorithmic steps for implementing recursion in a function are as follows: Step1 - Define a base case: Identify the simplest case for which the solution is known or trivial. This is the stopping condition for the recursion, as it prevents the function from infinitely calling itself. Step2 - Define a recursive case: Define the problem in terms of smaller subproblems. Break the problem down into smaller versions of itself, and call the function recursively to solve each subproblem. Step3 - Ensure the recursion terminates: Make sure that the recursive function eventually reaches the base case, and does not enter an infinite loop. step4 - Combine the solutions: Combine the solutions of the subproblems to solve the original problem. A Mathematical Interpretation Let us consider a problem that a programmer has to determine the sum of first n natural numbers, there are several ways of doing that but the simplest approach is simply to add the numbers starting from 1 to n. So the function simply looks like this, approach(1) Simply adding one by one f(n) = 1 + 2 + 3 +..+ n but there is another mathematical approach of representing this, approach(2) Recursive adding f(n) = 1 n=1 f(n) = n + f(n-1) n>1 There is a simple difference between the approach (1) and approach(2) and that is in approach(2) the function f( ) itself is being called inside the function, so this phenomenon is named recursion, and the function containing recursion is called recursive function, at the end, this is a great tool in the hand of the programmers to code some problems in a lot easier and efficient way. How are recursive functions stored in memory? Recursion uses more memory, because the recursive function adds to the stack with each recursive call, and keeps the values there until the call is finished. The recursive function uses LIFO (LAST IN FIRST OUT) Structure just like the stack data structure. https://www.geeksforgeeks.org/stack-data-structure/ What is the base condition in recursion?In the recursive program, the solution to the base case is provided and the solution to the bigger problem is expressed in terms of smaller problems. int fact(int n) { if (n < = 1) // base case return 1; else return n*fact(n-1); } In the above example, the base case for n < = 1 is defined and the larger value of a number can be solved by converting to a smaller one till the base case is reached. How a particular problem is solved using recursion?The idea is to represent a problem in terms of one or more smaller problems, and add one or more base conditions that stop the recursion. For e

geeksforgeeks.org

Recursion is a widely used idea in data structures and algorithms to solve complex problems by breaking them down into simpler ones. In this blog, we will understand the basic concepts of recursion and help you refine one of the critical problem-solving skills in data structures and algorithms. What do you mean by recursion? Recursion means "solving a problem using the solution of smaller subproblems (a smaller version of the same problem)" or "defining a problem in terms of itself." Recursion comes up in mathematics frequently, where we can find many examples of expressions written in terms of themselves. For example, calculating the value of the nth factorial and the nth Fibonacci numbers is one of the best examples. But recursion is just as much a programming concept! Finding the nth Factorial: n! = n * (n - 1)! Finding the nth Fibonacci: F(n) = F(n - 1) + F(n - 2) How recursion works in real life? Suppose you are standing in a long queue of people. How many people are directly behind you in the line? How can we solve this problem recursively? Rules One person can see only the person standing directly in front and behind. So, one can't just look back and count. Each person is allowed to ask questions from the person standing in front or behind. Solution You look behind and see if there is a person there. If not, then you can return the answer "0". If there is a person, repeat this step and wait for a response from the person standing behind. Once a person receives a response, they add 1 and respond to the person that asked them or the person standing in front of them. int peopleCount(Person currPerson) { if (noOneBehind(currPerson) == true) return 0 else { Person personBehind = currPerson.getBehind() return 1 + peopleCount(personBehind) } } How does recursion works in programming? In programming terms, recursion is a function calling itself until a "base condition" is true to produce the correct output. In other words, to solve a problem, we solve a problem that is a smaller instance of the same problem, and then use the solution to that smaller instance to solve the original problem. void function(input size) { base case .. .. ... function(smaller input size) //recursive call .. .. ... } int main() { ... .. ... function(input size) ... .. ... } For a recursive algorithm to work, smaller subproblems must eventually arrive at the base case. In simple words, any recursive algorithm has two parts: the base case and the recursive structure. Base case The base case is a terminating condition where a function immediately returns the result. This is the smallest version of the problem for which we already know the solution. Recursive structure The recursive structure is an idea to design a solution to a problem via the solution of its smaller sub-problems, i.e., the same problem but for a smaller input size. We continue calling the same problem for smaller input sizes until we reach the base case of recursion. Steps of problem-solving using recursion Define the base case: Think of the smallest version of the problem and write down the solution. Define the recursive structure: Assume we have a function to solve a problem of the given input size. Now we need to think: How could we use the problem's solution for a smaller input size to solve the problem for the given input size? In other words, how can we combine the solutions of the smaller subproblems to get the solution to the larger problem? Combine the base case and the recursive structure to generate a complete solution to the problem. Ideas to keep in mind while working with recursion Our code must cover all valid instances of smaller input sizes. We must have a correct base case that makes no recursive calls. When we make a recursive call, it should call a smaller instance and progress towards the base case. When we have a correct recursive structure and base case, then recursion would solve the problem for us. This is a "recursive leap of faith" where we should not worry abo

enjoyalgorithms.com