# 二叉树遍历

class TreeNode(object):
def __init__(self,data):
self.data=data
self.lchild=None
self.rchild=None


## 前序遍历

root-左-右

def pre_track(root):
if root:
print(root,end=",")
pre_track(root.lchild)
pre_track(root.rchild)


## 中序遍历

def in_track(root):
if root:
in_track(root.lchild)
print(root.data,end=",")
in_track(root.rchild)


## 后序遍历

def post_track(root):
if root:
post_track(root.lchild)
post_track(root.rchild)
print(root.data,end=",")


## 层次遍历

from collections import deque
def level_track(root):
if root:
queue=deque()
queue.append(root)
while len(queue)>0:
node=queue.popleft()
print(node.data,end-",")
if node.lchild:
queue.append(node.lchild)
if node.rchild:
queue.append(node.rchild)


## 重构

def TreeReconstruction(tpre,tin):
if len(tpre)==0
return None
root=TreeNode(tpre[0])
tin_index=tin.index(tpre[0])
left_tree=TreeReconstruction(tpre[1:tin_index+1], tin(:tin_index))
right_tree=TreeReconstruction(tpre[tin_index+1:], tin[tin_index+1:])
return root


# 二叉搜索树

## 构建及相关操作

def add(root,val):
if not root:
root=TreeNode(val)
else:
if root.data>val:
if root.data<val:
return root
def find(root,val):
if not root:
return False
if root.data==val:
return True
elif root.data>val:
return find(root.lchild,val)
else:
return find(root.rchild.val)
def delete(root,val):
if not root:
return
if root.data>val:
root.lchild = delete(root.lchild,val)
elif root.data<val:
root.lchild = delete(root.rchild,val)
else:
if not root.rchild and not root.lchild:
root=None
elif root.rchild:
root=root.rchild
elif root.lchild:
root=root.lchild
else:
cur=root
while cur.lchild:
cur=cur.lchild
root=cur
root.rchild=delete(root.rchild,cur.data)
return root


class BST(object):
def __init__(self,data=None):
self.root=TreeNode(data)
def find(self,val):
if not self.root:
return False
cur=self.root
while cur:
if cur.data==val:
return True
elif cur.data>val:
cur=cur.lchild
else:
cur=cur.rchild
return False
node=TreeNode(val
if not self.root:
self.root=node
return
if self.find(val):
return
cur=self.root
while cur:
pre=cur
if cur.data>val:
cur=cur.lchild
else:
cur=cur.rchild
if pre.data>val:
pre.lchild=node
else:
pre.rchild=node


04-25 395
11-26 6470

08-08 1065
08-20 508
12-28 151
02-14 261
08-26 88