MCPcopy Create free account
hub / github.com/HuberTRoy/leetCode / CBTInserter

Class CBTInserter

Tree/CompleteBinaryTreeInserter.py:69–132  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

67# self.right = None
68
69class CBTInserter(object):
70
71 def __init__(self, root):
72 """
73 :type root: TreeNode
74 """
75 self._root = root
76 self.root = TreeNode(root.val)
77 self.current_node = [self.root]
78 self._next_node = []
79 self.get_init_nodes()
80
81 def get_init_nodes(self):
82 result = []
83
84 current_nodes = [self._root]
85 _next_node = []
86
87 while current_nodes or _next_node:
88 for i in current_nodes:
89 if i.left:
90 result.append(i.left.val)
91 _next_node.append(i.left)
92
93 if i.right:
94 result.append(i.right.val)
95 _next_node.append(i.right)
96
97 current_nodes = _next_node
98 _next_node = []
99
100 for i in result:
101 self.insert(i)
102
103 def insert(self, v):
104 """
105 :type v: int
106 :rtype: int
107 """
108
109 node = self.current_node[-1]
110 if not node.left:
111 node.left = TreeNode(v)
112 parent = node
113 self._next_node.append(node.left)
114
115 elif not node.right:
116 node.right = TreeNode(v)
117 parent = node
118 self._next_node.append(node.right)
119 self.current_node.pop()
120
121 if not self.current_node:
122 self._next_node.reverse()
123 self.current_node = self._next_node
124 self._next_node = []
125
126 return parent.val

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected