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

    一、题目

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

    二、解法

     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     public int index = -1;
    16      String Serialize(TreeNode root) {
    17             StringBuffer sb = new StringBuffer();
    18             if(root == null){
    19                 sb.append("#,");
    20                 return sb.toString();
    21             }
    22             sb.append(root.val + ",");
    23             sb.append(Serialize(root.left));
    24             sb.append(Serialize(root.right));
    25             return sb.toString();
    26                 
    27      }
    28      TreeNode Deserialize(String str) {
    29            index++;
    30            int len = str.length();
    31            if(index >= len)
    32                return null;
    33            String[] strr = str.split(",");
    34            TreeNode node = null;
    35            if(!strr[index].equals("#")){
    36                node = new TreeNode(Integer.valueOf(strr[index]));
    37                node.left = Deserialize(str);
    38                node.right = Deserialize(str);
    39            }
    40            return node;
    41      }
    42 }
  • 相关阅读:
    springmvc
    POJ 3683 Priest John's Busiest Day
    POJ 3678 Katu Puzzle
    HDU 1815 Building roads
    CDOJ UESTC 1220 The Battle of Guandu
    HDU 3715 Go Deeper
    HDU 3622 Bomb Game
    POJ 3207 Ikki's Story IV
    POJ 3648 Wedding
    HDU 1814 Peaceful Commission
  • 原文地址:https://www.cnblogs.com/fankongkong/p/7462133.html
Copyright © 2011-2022 走看看