Simple C# Level-Order Travese beats 100%


  • 0
    T

    public class Solution {

    List<TreeNode> tn = new List<TreeNode>();
    
    IList<IList<int>> ret = new List<IList<int>>();
    bool r2l = true;
    
    private void helper()
    {
        List<TreeNode> next = new List<TreeNode>();
        List<int> cur = new List<int>();
        
        if(tn.Count == 0)
        {
            return;
        }
       
        
        
        foreach(TreeNode t in tn)
        {
                cur.Add(t.val);
                if(t.right != null) next.Add(t.right);  
                if(t.left != null)  next.Add(t.left);
        }
        
         
        if(!r2l)
        {
            cur.Reverse();
            r2l = true;
        }else{
            r2l = false;
        }
        tn = next;
        ret.Add(cur);
        helper();
        
    }
    public IList<IList<int>> ZigzagLevelOrder(TreeNode root) {
        if(root != null)
        {
            r2l = false;
            tn.Add(root);
            helper();
        }
        return ret;
    }
    

    }


Log in to reply
 

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