c# level traversal by using queue


  • 0
    N
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left;
     *     public TreeNode right;
     *     public TreeNode(int x) { val = x; }
     * }
     */
    public class Codec {
    
        // Encodes a tree to a single string.
        public string serialize(TreeNode root) {
            if (root==null) return null;
            var list = new List<string>();
            var q = new Queue<TreeNode>();
            q.Enqueue(root);
            while(q.Count>0){
                var count = q.Count;
                var node = q.Dequeue();
                
                if(node != null){
                    list.Add(node.val.ToString());  
                    q.Enqueue(node.left);
                    q.Enqueue(node.right);
                }
                else{
                    list.Add("#");
                }
            }
            
            return string.Join(",", list);
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(string data) {
            if(data == null) return null;
            var list = data.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries);
            if(list.Length == 0 ) return null;
            var root = new TreeNode(int.Parse(list[0]));
            var q = new Queue<TreeNode>();
            q.Enqueue(root);
            
            for(var i=1;i<list.Length;i=i+2){
                var node = q.Dequeue();
                
                if(!list[i].Equals("#")){
                    node.left = new TreeNode(int.Parse(list[i]));
                    q.Enqueue(node.left);
                }
                
                if(i+1<list.Length && !list[i+1].Equals("#")){
                    node.right = new TreeNode(int.Parse(list[i+1]));
                    q.Enqueue(node.right);
                }
            }
            
            return root;
        }
    }
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec = new Codec();
    // codec.deserialize(codec.serialize(root));
    

Log in to reply
 

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