My O(n) iterative solution using a queue in C#

  • 0

    I am using a modified BFS algorithm in which I push a tuple of node-level into the queue.

        public IList<int> RightSideView(TreeNode root)
            var list = new List<int>();        
            if(root == null) return list;
            var queue = new Queue<Tuple<TreeNode,int>>();
            int level = 0;
            queue.Enqueue(new Tuple<TreeNode, int>(root, level));
            while(queue.Count > 0)
                var tuple = queue.Dequeue();
                int l = tuple.Item2;
                var node = tuple.Item1;
                int val = node.val;
                if(l > level) {
                    level = l;
                if(node.right != null) queue.Enqueue(new Tuple<TreeNode, int>(node.right, l+1));
                if(node.left != null) queue.Enqueue(new Tuple<TreeNode, int>(node.left, l+1));
            return list;

Log in to reply

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