二叉树的序列化
来源:互联网 发布:油画淘宝详情页模版 编辑:程序博客网 时间:2024/06/05 16:35
首先我们介绍二叉树先序序列化的方式,假设序列化的结果字符串为str,初始时str等于空字符串。先序遍历二叉树,如果遇到空节点,就在str的末尾加上“#!”,“#”表示这个节点为空,节点值不存在,当然你也可以用其他的特殊字符,“!”表示一个值的结束。如果遇到不为空的节点,假设节点值为3,就在str的末尾加上“3!”。现在请你实现树的先序序列化。
给定树的根结点root,请返回二叉树序列化后的字符串。
我的提交
# -*- coding:utf-8 -*-# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass TreeToString: def toString(self, root): # write code here if not root: return '#!' stack = [] string = '' stack.append(root) while stack: node = stack.pop() if node: string += str(node.val) + '!' stack.append(node.right) stack.append(node.left) else: string += '#!' return string
参考答案
/*struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { }};*/class TreeToString {public: string getString(int x){ string ret; while(x) ret += '0' + (x % 10),x /= 10; reverse(ret.begin(),ret.end()); return ret; } void convert(TreeNode* root,string &ret){ if(root == NULL){ ret = ret + "#!"; return; } ret = ret + getString(root->val) + "!"; convert(root->left,ret); convert(root->right,ret); } string toString(TreeNode* root) { string ret; convert(root,ret); return ret; }};
阅读全文
0 0
- 二叉树的序列化
- 二叉树的序列化
- 二叉树的序列化
- 二叉树的序列化
- 二叉树的序列化
- 二叉树的序列化
- 二叉树的序列化
- 二叉树序列化
- 二叉树序列化
- 序列化二叉树
- 序列化二叉树
- 序列化二叉树
- 序列化二叉树
- 序列化二叉树
- 序列化二叉树
- 序列化二叉树
- 序列化二叉树
- 序列化二叉树
- input框中的文字加下划线
- Hive创建表
- LeetCode-75. Sort Colors
- Spring Boot将WAR文件部署到Tomcat
- 最小的K个数的多种解法
- 二叉树的序列化
- axios 使用文档
- Jenkins启动slave的方法
- Effective STL 24 Choose carefully between map::operator[] and map::insert
- 设计模式的应用场景(11)--组合模式
- 记录一次自定义参数绑定错误问题的解决过程
- CodeForces
- EasyNVR H5无插件直播方案前端构建之:引用videojs无法自动播放
- 【算法】字符串循环左移K位