c# BFS


  • 0
    V
    public IList<int> LargestValues(TreeNode root) {
            var list = new List<int>();
            if(root == null){return list;}
            
            var t = root; var q = new Queue<TreeNode>(); int max = int.MinValue;
            q.Enqueue(t); q.Enqueue(null);
            
            while(q.Count > 0){
                var node = q.Dequeue();
                if(node == null){
                    if(q.Count > 0){ q.Enqueue(null); }
                    list.Add(max);
                    max = int.MinValue;
                }else{
                    if(node.val >= max){ max = node.val; }
                    if(node.left != null) {q.Enqueue(node.left); }
                    if(node.right != null) {q.Enqueue(node.right);}
                }
            }
            return list;
        }
    

Log in to reply
 

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