BFS and DFS Solutions


  • 1

    BFS:

        public int FindBottomLeftValue(Treenode root)
        {
            Queue<Treenode> Q = new Queue<Treenode>();
            Q.Enqueue(root);
    
            Treenode result = null;
    
            while (Q.Any())
            {
                result = Q.Peek();
                int count = Q.Count;
                while (count > 0)
                {
                    Treenode temp = Q.Dequeue();
    
                    if (temp.left != null) Q.Enqueue(temp.left);
                    if (temp.right != null) Q.Enqueue(temp.right);
    
                    count--;
                }
            }
            return result.data;
        }
    

    DFS:

        public static int FindBottomLeftValue(Treenode root)
        {
            FindBottomLeftValue(root, 1);
            return storage.bottomleftvalue;
        }
        public static void FindBottomLeftValue(Treenode root, int currLevel)
        {
    
            if (currLevel > storage.maxlevel)
            {
                storage.bottomleftvalue = root.data;
                storage.maxlevel++;
            }
            if (root.left != null)
                FindBottomLeftValue(root.left, currLevel + 1);
    
            if (root.right != null)
                FindBottomLeftValue(root.right, currLevel + 1);
        }
    
        class storage
        {
            public static int maxlevel = 0;
            public static int bottomleftvalue = 0;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.