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);
        }
    }
    
  • 相关阅读:
    解决方案solution
    Marshal类
    鼠标钩子WH_MOUSE_LL和WH_MOUSE的区别
    DllImport
    打包.py文件成.exe
    C++定义全部变量注意项
    类.cpp文件不识别类.h所定义的结构体问题
    C++判断文件是否存在
    博客专栏
    软件测试基础知识
  • 原文地址:https://www.cnblogs.com/ggmfengyangdi/p/5828616.html
Copyright © 2011-2022 走看看