-
Notifications
You must be signed in to change notification settings - Fork 17
/
encode-n-ary-tree-to-binary-tree.py
69 lines (49 loc) · 1.62 KB
/
encode-n-ary-tree-to-binary-tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from collections import deque
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
# Encodes an n-ary tree to a binary tree.
def encode(self, root: "Node") -> TreeNode:
if not root:
return
queue = deque()
broot = TreeNode(root.val)
queue.append([root, broot])
while queue:
nnode, bnode = queue.popleft()
bchild_prev = TreeNode(None) # dummy node
for nchild in nnode.children:
bchild = TreeNode(nchild.val)
queue.append([nchild, bchild])
bnode.left = bnode.left or bchild
bchild_prev.right = bchild
bchild_prev = bchild
return broot
# Decodes your binary tree to an n-ary tree.
def decode(self, data: TreeNode) -> "Node":
if not data:
return
queue = deque()
nroot = Node(data.val, [])
queue.append([nroot, data])
while queue:
nnode, bnode = queue.popleft()
bchild = bnode.left
while bchild:
nchild = Node(bchild.val, [])
nnode.children.append(nchild)
queue.append([nchild, bchild])
bchild = bchild.right
return nroot
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(root))