C# Preorder Traversal and Level Order Traversal


  • 0
    S
    //BFS Level Order Traversal
    public class Codec {
    
    // Encodes a tree to a single string.
    public string serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        Queue<TreeNode> q = new Queue<TreeNode>();
        q.Enqueue(root);
        while(q.Count>0){
            TreeNode tn = q.Dequeue();
            if(tn!=null){
                q.Enqueue(tn.left);
                q.Enqueue(tn.right);
                sb.Append(tn.val);
                sb.Append(",");
            }else{
                sb.Append('#');
                sb.Append(",");
            }
        }
        sb.Length-=1;
        return sb.ToString();
    }
    
    // Decodes your encoded data to tree.
    public TreeNode deserialize(string data) {
        string[] strs=data.Split(',');
        if(strs[0]=="#")return null;
        TreeNode root=new TreeNode(Convert.ToInt32(strs[0]));
        Queue<TreeNode> q = new Queue<TreeNode>();
        q.Enqueue(root);
        for(int i=1;i<strs.Length;i+=2){
            TreeNode parent = q.Dequeue();
            TreeNode left = strs[i]=="#"?null:new TreeNode(Convert.ToInt32(strs[i]));
            TreeNode right = strs[i+1]=="#"?null:new TreeNode(Convert.ToInt32(strs[i+1]));
            parent.left=left;parent.right=right;
            if(left!=null)q.Enqueue(left);
            if(right!=null)q.Enqueue(right);
        }
        return root;
    }
    }
    
    
    
    //DFS Preorder Traversal
    public class Codec {
    
    // Encodes a tree to a single string.
    public string serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        serialize(root,sb);
        sb.Length-=1;
        return sb.ToString();
    }
    public void serialize(TreeNode root,StringBuilder sb){
        if(root==null){
            sb.Append("#,");return;
        }
        sb.Append(root.val);
        sb.Append(",");
        serialize(root.left,sb);
        serialize(root.right,sb);
    }
    // Decodes your encoded data to tree.
    public TreeNode deserialize(string data) {
       string[] strs = data.Split(',');
       int pos = 0;
       return deserialize(strs,ref pos);
    }
    public TreeNode deserialize(string[] strs, ref int pos){
        if(strs[pos]=="#")return null;
        TreeNode root = new TreeNode(Convert.ToInt32(strs[pos]));
        pos++;
        root.left = deserialize(strs,ref pos);
        pos++;
        root.right = deserialize(strs,ref pos);
        return root;
    }
    

    }


Log in to reply
 

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