What in layman's terms is a Recursive Function using PHP

前端 未结 16 1330
庸人自扰
庸人自扰 2020-11-22 05:50

Can anyone please explain a recursive function to me in PHP (without using Fibonacci) in layman language and using examples? i was looking at an example but the Fibonacci to

16条回答
  •  悲哀的现实
    2020-11-22 06:33

    Its a function that calls itself. Its useful for walking certain data structures that repeat themselves, such as trees. An HTML DOM is a classic example.

    An example of a tree structure in javascript and a recursive function to 'walk' the tree.

        1
       / \
      2   3
         / \
        4   5
    

    --

    var tree = {
      id: 1,
      left: {
        id: 2,
        left: null,
        right: null
      },
      right: {
        id: 3,
        left: {
          id: 4,
          left: null,
          right: null
        },
        right: {
          id: 5,
          left: null,
          right: null
        }
      }
    };
    

    To walk the tree, we call the same function repeatedly, passing the child nodes of the current node to the same function. We then call the function again, first on the left node, and then on the right.

    In this example, we'll get the maximum depth of the tree

    var depth = 0;
    
    function walkTree(node, i) {
    
      //Increment our depth counter and check
      i++;
      if (i > depth) depth = i;
    
      //call this function again for each of the branch nodes (recursion!)
      if (node.left != null) walkTree(node.left, i);
      if (node.right != null) walkTree(node.right, i);
    
      //Decrement our depth counter before going back up the call stack
      i--;
    }
    

    Finally we call the function

    alert('Tree depth:' + walkTree(tree, 0));
    

    A great way of understanding recursion is to step through the code at runtime.

提交回复
热议问题