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

    题目描述

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

    解题思路

    使用前序遍历,将遇到的结点添加到字符串中,遇到null则将一个#添加要序列化字符串中。反序列化时,每次读取根结点,然后读取其左结点,遇到#(null)时,返回上层。

    实现

    /*树结点定义*/
    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
    
        public TreeNode(int val) {
            this.val = val;
    
        }
    
    }
    /*实现*/
    public class Solution {
        String Serialize(TreeNode root) {
            StringBuilder sb = new StringBuilder();
            serialize(root, sb);
            return sb.toString();
        }
    
        private void serialize(TreeNode root, StringBuilder sb) {
            if (root == null) {
                sb.append("#,");
                return;
            }
    
            sb.append(root.val + ",");
            serialize(root.left, sb);
            serialize(root.right, sb);
        }
    
        private class Result{
            TreeNode node;
            int pos;
    
            Result(TreeNode node, int pos){
                this.node = node;
                this.pos = pos;
            }
        }
    
        TreeNode Deserialize(String str) {
            if (str == null || str.length() <= 0) return null;
            String[] strs = str.split(",");
            Result re = deserialize(strs, 0);
            return re.node;
        }
    
        private Result deserialize(String[] str, int i) {
            TreeNode root = null;
            if (i < str.length - 1){
                if ("#".equals(str[i])) return new Result(null, i+1);
                root = new TreeNode(Integer.parseInt(str[i]));
                Result l = deserialize(str, i + 1);
                root.left = l.node;
                Result r = deserialize(str, l.pos);
                root.right = r.node;
                return new Result(root, r.pos);
            }
            return new Result(root, i+1);
        }
    }
    
  • 相关阅读:
    斯坦福机器学习视频之线性回归习题详解
    linuxc程序设计之passwd与shadow解析(转)
    DeepLearning之MLP解析
    The Linux Environment之getopt_long()
    插入排序
    堆排序
    归并排序
    快速排序
    CyclicBarrier与CountDownLatch的区别
    判断是否是平衡二叉树(左子树与右子树高度不大于1)
  • 原文地址:https://www.cnblogs.com/ggmfengyangdi/p/5828616.html
Copyright © 2011-2022 走看看