/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */publicclassCodec {// Encodes a tree to a single string.publicStringserialize(TreeNode root) {if (root ==null) returnnull;StringBuilder sb =newStringBuilder();Stack<TreeNode> stack =newStack<>();stack.push(root);while (!stack.isEmpty()) {TreeNode node =stack.pop();sb.append(node.val).append(",");if (node.right!=null) stack.push(node.right);if (node.left!=null) stack.push(node.left); }returnsb.toString(); }// Decodes your encoded data to tree.publicTreeNodedeserialize(String data) {if (data ==null||data.length() ==0) returnnull;String[] arr =data.split(",");Queue<Integer> queue =newLinkedList<>();for (String val : arr) {queue.offer(Integer.parseInt(val)); }returnbuildTree(queue); }privateTreeNodebuildTree(Queue<Integer> queue) {if (queue.isEmpty()) returnnull;TreeNode root =newTreeNode(queue.poll());Queue<Integer> smallerQueue =newLinkedList<>();while (!queue.isEmpty() &&queue.peek() <root.val) smallerQueue.offer(queue.poll());root.left=buildTree(smallerQueue);root.right=buildTree(queue);return root; }}// Your Codec object will be instantiated and called as such:// Codec codec = new Codec();// codec.deserialize(codec.serialize(root));