序列化和反序列化二叉树

小灰灰 2022-05-24 08:54 358阅读 0赞

这里写图片描述

  1. import java.util.*;
  2. class TreeNode {
  3. int val = 0;
  4. TreeNode left = null;
  5. TreeNode right = null;
  6. public TreeNode(int val) {
  7. this.val = val;
  8. }
  9. }
  10. public class Solution {
  11. int index=-1;
  12. //序列化,将对象转换成字符串
  13. String Serialize(TreeNode root) {
  14. StringBuilder sb=new StringBuilder();
  15. if(root==null){
  16. sb.append("#,");
  17. return sb.toString();
  18. }
  19. sb.append(root.val+",");
  20. sb.append(Serialize(root.left));
  21. sb.append(Serialize(root.right));
  22. return sb.toString();
  23. }
  24. //反序列化
  25. TreeNode Deserialize(String str) {
  26. index++;
  27. String[]arr=str.split(",");
  28. TreeNode node=null;
  29. if(!arr[index].equals("#")){
  30. node=new TreeNode(Integer.valueOf(arr[index]));
  31. node.left=Deserialize(str);
  32. node.right=Deserialize(str);
  33. }
  34. return node;
  35. }
  36. //二叉树的层序遍历
  37. public String TreeBFS(TreeNode pRoot,String str)
  38. {
  39. Queue<TreeNode> arr=new LinkedList<TreeNode>();//存放元素的队列
  40. arr.offer(pRoot);
  41. boolean flag=false;
  42. while(!arr.isEmpty())
  43. {
  44. TreeNode temp=arr.poll();
  45. // System.out.println(temp.val);
  46. str+=temp.val;
  47. if(temp.left!=null)
  48. {
  49. arr.offer(temp.left);
  50. }
  51. if(temp.right!=null)
  52. {
  53. arr.offer(temp.right);
  54. }
  55. }
  56. System.out.println(str);
  57. return str;
  58. }
  59. public static void main(String[]args){
  60. //System.out.println("Hello");
  61. TreeNode root=new TreeNode(1);
  62. root.left=new TreeNode(2);
  63. root.right=new TreeNode(3);
  64. root.left.left=new TreeNode(4);
  65. root.left.right=new TreeNode(5);
  66. root.right.left=new TreeNode(6);
  67. root.right.right=new TreeNode(7);
  68. Solution s=new Solution();
  69. String str="";
  70. s.TreeBFS(root,str);
  71. }
  72. }

发表评论

表情:
评论列表 (有 0 条评论,358人围观)

还没有评论,来说两句吧...

相关阅读

    相关 序列/序列

    二叉树被记录成文件的过程,为二叉树的序列化 通过文件重新建立原来的二叉树的过程,为二叉树的反序列化 设计方案并实现。 (已知结点类型为32位整型) 思路:先序遍历实现。