import java.util.LinkedList; import java.util.Queue; public class Solution { String Serialize(TreeNode root) { StringBuilder sb = new StringBuilder(); if(root==null) { sb.append("#,"); return sb.toString(); } sb.append(String.valueOf(root.val)); sb.append(‘,‘); sb.append(Serialize(root.left)); sb.append(Serialize(root.right)); return sb.toString(); } TreeNode Deserialize(String str) { String[] values = str.split(","); Queue<String> queue = new LinkedList<>(); for(int i=0;i<values.length;i++) { queue.offer(values[i]); } return reconPreOrder(queue); } private TreeNode reconPreOrder(Queue<String> queue) { String value = queue.poll(); if(value.equals("#")) { return null; } TreeNode head = new TreeNode(Integer.valueOf(value)); head.left = reconPreOrder(queue); head.right = reconPreOrder(queue); return head; } }
原文地址:https://www.cnblogs.com/figsprite/p/10676365.html
时间: 2024-10-08 22:45:45