zoukankan      html  css  js  c++  java
  • 序列化二叉树

    请实现两个函数,分别用来序列化和反序列化二叉树

    Java:

     1 /*
     2 public class TreeNode {
     3     int val = 0;
     4     TreeNode left = null;
     5     TreeNode right = null;
     6 
     7     public TreeNode(int val) {
     8         this.val = val;
     9 
    10     }
    11 
    12 }
    13 */
    14 public class Solution {
    15     private String s ;
    16     
    17     String Serialize(TreeNode root) {
    18         if (root == null){
    19             return "#" ;
    20         }
    21         return root.val + " " + Serialize(root.left) + " " + Serialize(root.right) ;
    22     }
    23     TreeNode Deserialize(String str) {
    24         s = str ;
    25         return Deserialize() ;
    26     }
    27     
    28     TreeNode Deserialize() {
    29         if (s.length() == 0)
    30             return null ;
    31         int index = s.indexOf(' ') ;
    32         String node = index == -1 ? s : s.substring(0,index) ;
    33         s = index == -1 ? "" : s.substring(index+1) ;
    34         if (node.equals("#"))
    35             return null ;
    36         int val = Integer.valueOf(node) ;
    37         TreeNode t = new TreeNode(val) ;
    38         t.left = Deserialize() ;
    39         t.right = Deserialize() ;
    40         return t ;
    41     }
    42 }
  • 相关阅读:
    Python爬虫实验报告之Big_Homework2_Douyu
    Python_dict
    Common sequence manipulation functions
    python基于opencv库的人脸识别总结
    使用cwrsync同步windows文件到linux
    搭建mosquitto
    docker搭建mqtt
    docker部署gofastdfs
    ap配置
    冒泡排序
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/10621854.html
Copyright © 2011-2022 走看看