Simple, neat level order making using of nulls


  • 0
    V
    public int FindBottomLeftValue(TreeNode root) {
            var t = root; var q = new Queue<TreeNode>();
            q.Enqueue(t);
            q.Enqueue(null);
            TreeNode last = t;
            
            while(q.Count > 0) {
                var node = q.Dequeue();
                if(node == null) {
                    if(q.Count > 0)
                    {
                        last = q.Peek();
                        q.Enqueue(null);
                    }
                }
                else {
                    if(node.left != null) {
                        q.Enqueue(node.left);
                    }
                    if(node.right != null) {
                        q.Enqueue(node.right);
                    }
                }
            }
            
            return last.val;
        }
    

Log in to reply
 

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