R
R
Razer15112022-03-24 21:27:26
C++ / C#
Razer1511, 2022-03-24 21:27:26

Why is the CW stitch being repeated?

Good afternoon. I'm learning C# and ran into some misunderstanding about how a function works.
At the moment I am solving problems using algorithms, namely, bypassing a binary tree.

Binary tree class:

class Node<T>
    {
        public int Value;
        public Node<T> Left;
        public Node<T> Right;
    }


Method for adding values:

public void InsertValues(int value)
        {
            if (value > Value)
            {
                if (Right is null)
                    Right = new Node<T> { Value = value };
                else
                    Right.InsertValues(value);
            } 
            else
            {
                if (Left is null)
                    Left = new Node<T> { Value = value };
                else
                    Left.InsertValues(value);
            }
        }


Infix tree traversal:

public void Infix(Node<T> node)
        {
            if (node.Left != null)
            {
                Infix(node.Left);
            }
            Console.WriteLine(node.Value);
            if (node.Right != null)
            {
                Infix(node.Right);
            }
        }


Challenges:

class Program
    {
        static void Main(string[] args)
        {
            Node<int> node = new Node<int> { Value = 2 };
            node.InsertValues(3);
            node.InsertValues(1);
            node.Infix(node);
        }
    }


The essence of the question: Why, after the first call to the line in the Infix bypass if (node.Right != null) , when we see that node.Right == null, we do not complete the execution of the function (skipping the loop), but return back to the line Console .WriteLine(node.Value); ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ananiev, 2022-03-25
@SaNNy32

There is no cycle here. And there is recursion. Learn how recursion works

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question