Search code examples
c#recursiontreeglobal-variables

Reassigning a global variable in a recursive call


I am trying out a problem and here is my code .

class Program
    {
        static void Main(string[] args)
        {
            Solution s = new Solution();
            s.CreateTree();
        }
    }

    

 public class TreeNode {
     public int val;
     public TreeNode left;
     public TreeNode right;
     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
         this.val = val;
         this.left = left;
         this.right = right;
     }
 }
 
 public class Solution
    {
        static TreeNode n1;
        //static or instance , didn't make any difference
        Queue<TreeNode> q = new Queue<TreeNode>();
        public TreeNode IncreasingBST(TreeNode root)
        {
            TraverseAndCreateTree(root);
            var rootNodeOfResultantTree = q.Dequeue();
            return rootNodeOfResultantTree;
        }

        public void CreateTree()
        {            
            TreeNode t = new TreeNode(5);
            t.left = new TreeNode(3);
            t.right = new TreeNode(6);
            t.left.left = new TreeNode(2);
            t.left.right = new TreeNode(4);
            t.left.left.left = new TreeNode(1);
            t.right.right = new TreeNode(8);
            t.right.right.left = new TreeNode(7);
            t.right.right.right = new TreeNode(9);
            IncreasingBST(t);
        }

        public void TraverseAndCreateTree(TreeNode root)
        {
            if (root == null)
            {
                return;
            }
            TraverseAndCreateTree(root.left);
            n1 = new TreeNode(root.val);
            q.Enqueue(n1);
            n1 = n1.right;   
            //reassigned the global variable
            TraverseAndCreateTree(root.right);
              

        }
    }

I am aware that code is not correct for the problem but I am not able to understand why global variable reassignment doesn't work . I was expecting my global variable n1 to be reassigned as its right child Node and get its value . But this doesn't happen . When inspecting the first value in q , its right and left child are both null .

left and right child nodes are null

What could be the reason for this ? Is global variable not be shared across all call stack entries and if changed in one of the entries , should get reflected in all ?


Solution

  • My code was wrong as I was assigning

    n1 = new TreeNode(root.val);
    q.Enqueue(n1);
    n1 = n1.right;
    

    At this point n1.right is null and hence n1 becomes null and no relationship established between two entries in the Queue.

    I corrected after assigning

    n1.right = new TreeNode(root.val);
    q.Enqueue(n1);
    n1 = n1.right;