C# Accepted solution with Queue


  • 0
    A
    // Encodes a tree to a single string.
                public string serialize(TreeNode root)
                {
                    var result = "null";
                    if (root == null) return result;
                    result = root.val.ToString();
                    result += ",l" + serialize(root.left);
                    result += ",r" + serialize(root.right);
                    return result;
                }
    
                // Decodes your encoded data to tree.
                public TreeNode deserialize(string data)
                {
                    if (string.IsNullOrEmpty(data) || data == "null") return null;
                    var dataArray = data.Split(',');
                    var queue = new Queue<string>(dataArray);
                    var root = new TreeNode(Convert.ToInt32(queue.Dequeue()));
                    deserialize(ref queue, ref root);
                    return root;
                }
    
                public void deserialize(ref Queue<string> queue, ref TreeNode root)
                {
                    var nextItem = queue.Dequeue();
                    if (nextItem.StartsWith("l"))
                    {
                        var nextItemValue = nextItem.Substring(1);
                        if (nextItemValue == "null")
                        {
                            root.left = null;
                        }
                        else
                        {
                            root.left = new TreeNode(Convert.ToInt32(nextItemValue));
                            deserialize(ref queue, ref root.left);
                        }
                    }
                    nextItem = queue.Dequeue();
                    if (nextItem.StartsWith("r"))
                    {
                        var nextItemValue = nextItem.Substring(1);
                        if (nextItemValue == "null")
                        {
                            root.right = null;
                        }
                        else
                        {
                            root.right = new TreeNode(Convert.ToInt32(nextItemValue));
                            deserialize(ref queue, ref root.right);
                        }
                    }
                }
    

Log in to reply
 

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