http://www.careercup.com/question?id=4868040812396544

You should transform an structure of multiple tree from machine A to machine B. It is a serialization and deserialization problem, but i failed to solve it well.

You could assume the struct is like this:

struct Node{
string val;
vector<Node*> sons;
}

and in machine A, you will given the point to root Node, and in machine B,you should return a pointer to root Node.

class Node:
def __init__(self, val):
self.val = val
self.sons = [] class Solution:
def __init__(self, root):
self.sequence = str(root.val)
cur = [root]
while cur:
next = []
for i in cur:
self.sequence += str(len(i.sons))
for ii in i.sons:
next.append(ii)
self.sequence += str(ii.val)
cur = next def de_serial(self):
strs = self.sequence
# print strs
idx = 1
cur = [Node(int(strs[0]))]
root = cur[0]
while cur and idx < len(strs):
next = []
for i in cur:
num = int(strs[idx])
# print 'num', num
idx += 1 # notice this, idx increment not in while but in for
for j in range(num):
tmp = Node(int(strs[idx]))
# print tmp.val
i.sons.append(tmp)
next.append(tmp)
idx += 1 cur = next
# print map(lambda x: x.val, next)
return root if __name__ == "__main__":
tree = Node(1)
two = Node(2)
three = Node(3)
four = Node(4)
five = Node(5)
six = Node(6)
seven = Node(7)
tree.sons = [two, three, four]
two.sons = [five]
three.sons = [six, seven]
a = Solution(tree)
print a.de_serial()

先序遍历+中序遍历 唯一确定一棵树, 前提是树是二叉树,树的所有节点值不同

class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None class Solution:
def __init__(self):
self.pre = []
self.ino = [] def preorder(self, root, list):
if not root: return
list.append(root.val)
self.preorder(root.left, list)
self.preorder(root.right, list) def inorder(self, root, lists):
if not root: return
self.inorder(root.left, lists)
lists.append(root.val)
self.inorder(root.right, lists) def serialization(self, root):
self.preorder(root, self.pre)
self.inorder(root, self.ino) def de_serial(self):
return self.de_serialization(self.pre, self.ino) def de_serialization(self, pre, inorder):
if not pre: return None
root = Node(pre[0])
i = 0
while i < len(inorder):
if pre[0] == inorder[i]:
break
i += 1 root.left = self.de_serialization(pre[1:i+1], inorder[:i])
root.right = self.de_serialization(pre[i+1:], inorder[i+1:])
return root if __name__ == "__main__":
a = Solution()
tree = Node(0)
tree.left = Node(1)
tree.right = Node(2)
a.serialization(tree)
root = a.de_serial()
print root.val, root.left.val, root.right.val

谷歌面经 Tree Serialization的更多相关文章

  1. [LintCode] Binary Tree Serialization

    Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a ...

  2. Lintcode: Binary Tree Serialization (Serialization and Deserialization Of Binary Tree)

    Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a ...

  3. override toString() function for TreeNode to output OJ's Binary Tree Serialization

    class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } @Override publ ...

  4. [LeetCode] Binary Tree Zigzag Level Order Traversal

    Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to ...

  5. [Leetcode] Recover Binary Search Tree

    Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...

  6. [LeetCode] Serialize and Deserialize Binary Tree

    Serialize and Deserialize Binary Tree Serialization is the process of converting a data structure or ...

  7. ✡ leetcode 156. Binary Tree Upside Down 旋转树 --------- java

    156. Binary Tree Upside Down Add to List QuestionEditorial Solution My Submissions   Total Accepted: ...

  8. 【LeetCode】101 - Symmetric Tree

    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For e ...

  9. 【LeetCode】Binary Tree Level Order Traversal II

    Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left ...

随机推荐

  1. 理解 Soap

    http://www.cnblogs.com/yhuang/archive/2012/04/04/share_storm.html 自己也写了下: using System; using System ...

  2. 基于Criminisi算法的栅格影像数据敏感地物隐藏

    栅格影像数据敏感地物伪装是指通过计算机智能识别与计算,将影像数据中的敏感地物进行识别与提取,将敏感地物智能替换成公共地物,如草地.森林.湖泊.公园等.但目前该技术并不成熟,同时栅格影像数据敏感地物伪装 ...

  3. [C++] socket - 5 [API事件对象实现线程同步]

    /*API事件对象实现线程同步*/ #include<windows.h> #include<stdio.h> DWORD WINAPI myfun1(LPVOID lpPar ...

  4. ThreadLocal线程范围内的共享变量

    模拟ThreadLocal类实现:线程范围内的共享变量,每个线程只能访问他自己的,不能访问别的线程. package com.ljq.test.thread; import java.util.Has ...

  5. Atitit.Hibernate中Criteria 使用总结and 关联查询 and 按照子对象查询 o9o

    Atitit.Hibernate中Criteria 使用总结and 关联查询 and 按照子对象查询 o9o 1. Criteria,,Criterion ,, 1 <2. 主要的对象黑头配置磊 ...

  6. paip.微信菜单直接跳转url和获取openid流程总结

    paip.微信菜单直接跳转url和获取openid流程总结   #------不能直接跳转,贝儿提示不安全的链接.. #-------使用auth跳转. //todox 直接转到..  direct ...

  7. paip.hibernate save 失败的解决

    paip.hibernate save 失败的解决   打开log  debug  level,,看不见insert 代码...     Hibernate select max(ID).txt   ...

  8. paip.java OutOfMemoryError 解决方法o33

    paip.java OutOfMemoryError 解决方法o33 java.lang.OutOfMemoryError: Requested # java.lang.OutOfMemoryErro ...

  9. Eclipse连接到My sql数据库之前操作

    Eclipse连接到My sql数据库之前操作 1:首先是安装My sql数据库(为了减少你的麻烦,按照下面的连接,下载即可)百度云链接:http://pan.baidu.com/s/1mitWmbm ...

  10. Liferay7 BPM门户开发之27: MVC Portlet插件工程开发

    官网上的教材说实话实在精简不清晰. https://dev.liferay.com/develop/tutorials/-/knowledge_base/7-0/creating-an-mvc-por ...