def _build_bst(lst): l = len(lst) if l == 0: return None if l == 1: return BNode(lst[0]) return BNode(lst[l//2], _build_bst(lst[:(l//2)]), _build_bst(lst[(l//2)+1:]))
def _insert(root): if data < root.get_data(): if root.get_left() is None: root.set_left(BNode(data)) else: _insert(root.get_left()) else: if root.get_right() is None: root.set_right(BNode(data)) else: _insert(root.get_right())
def _buildpostin(post, ino, current): if len(ino) == 0: _buildpostin.pointer += 1 return None if len(ino) == 1: return BNode(ino[-1]) _buildpostin.pointer -= 1 current.set_right(_buildpostin(post, ino[ino.index(current.get_data())+1:], BNode(post[_buildpostin.pointer]))) _buildpostin.pointer -= 1 current.set_left(_buildpostin(post, ino[:ino.index(current.get_data())], BNode(post[_buildpostin.pointer]))) return current
def insert(self, data): def _insert(root): if data < root.get_data(): if root.get_left() is None: root.set_left(BNode(data)) else: _insert(root.get_left()) else: if root.get_right() is None: root.set_right(BNode(data)) else: _insert(root.get_right()) if self.get_root() is None: self.set_root(BNode(data)) else: _insert(self.get_root())
def build_post_in(self, post, ino): def _buildpostin(post, ino, current): if len(ino) == 0: _buildpostin.pointer += 1 return None if len(ino) == 1: return BNode(ino[-1]) _buildpostin.pointer -= 1 current.set_right(_buildpostin(post, ino[ino.index(current.get_data())+1:], BNode(post[_buildpostin.pointer]))) _buildpostin.pointer -= 1 current.set_left(_buildpostin(post, ino[:ino.index(current.get_data())], BNode(post[_buildpostin.pointer]))) return current _buildpostin.pointer = len(post) - 1 self.set_root(_buildpostin(post, ino, BNode(post[-1]))) return self.get_root()
def build_pre_in(self, pre, ino): def _buildprein(pre, ino, current): if len(ino) == 0: _buildprein.pointer -= 1 return None if len(ino) == 1: return BNode(ino[0]) _buildprein.pointer += 1 current.set_left(_buildprein(pre, ino[:ino.index(current.get_data())], BNode(pre[_buildprein.pointer]))) _buildprein.pointer += 1 current.set_right(_buildprein(pre, ino[ino.index(current.get_data())+1:], BNode(pre[_buildprein.pointer]))) return current _buildprein.pointer = 0 self.set_root(_buildprein(pre, ino, BNode(pre[0]))) return self.get_root()