顺序结构和链式结构对比:
L=[1,2,3,4]
L.append(10)#尾部添加
L.insert(1,20)#插入元素
L.remove(3)#删除元素
L[4]=30#修改元素
L.index(2)#查找元素
单链表:
# 创建节点类
class Node:
def __init__(self, value):
self.value = value
self.next = None
# 创建单链表类
class SingleList:
def __init__(self):
self.head = Node(None) # 初始化头结点为空节点
self.length = 0 # 链表长度
# 给一个列表,初始化链表
def init_slist(self, l):
p = self.head
if not l:
return
for i in l:
p.next = Node(i)
self.length += 1
p = p.next
# 往链表里添加元素
# 在pre_item(节点的值)后面添加元素,元素节点的值为value
def append_slist(self, pre_item, value):
p = self.head.next
while p:
if p.value == pre_item:
n = Node(value)
n.next = p.next
p.next = n
self.length += 1
return
else:
p = p.next
return
# 头部插元素
def head_append(self, item):
p = self.head
n = Node(item)
n.next = p.next
p.next = n
self.length += 1
# 尾部插元素
def tail_append(self, item):
p = self.head
while p.next:
p = p.next
p.next = Node(item)
self.length += 1
# 从链表里删除元素
def delete_slist(self, value):
pre = self.head # 前一个节点
p = self.head.next # 从第一个节点开始
flag = False # 未找到标志位
while p:
if p.value == value:
pre.next = p.next
p = p.next
self.length -= 1
flag = True
break
else:
pre = p
p = p.next
if not flag:
print('value not in list')
# 链表判空
def is_empty(self):
if self.head.next is None:
return True
else:
return False
# 清空链表
def clear_slist(self):
self.head.next = None
self.length = 0
# 查询链表第几个节点的值(从1开始)
def search_slist(self, index):
if index > self.length:
error = "Index out of range"
return error
else:
p = self.head
count = 0
while count < index:
p = p.next
count += 1
return p.value
# 遍历链表
def travel_slist(self):
l = [] # 按链表顺序存放链表的值
p = self.head.next
while p != None:
l.append(p.value)
p = p.next
return l
栈的顺序存储结构:
# 自定义栈异常
class StackError(Exception):
pass
# 基于列表实现顺序栈
class SStack:
def __init__(self):
# 约定列表最后一个元素为栈顶
self._elems = []
# 弹出栈顶元素
def top(self):
if not self._elems:
raise StackError('stack is empty')
return self._elems[-1]
# 判断栈是否为空
def is_empty(self):
return self._elems == []
# 入栈
def push(self, elem):
self._elems.append(elem)
# 出栈
def pop(self):
if not self._elems:
raise StackError('stack is empty')
return self._elems.pop()
栈的链式存储结构(头为栈顶):
# 自定义栈异常
class StackError(Exception):
pass
# 创建结点类
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LStack:
def __init__(self):
# 标记栈顶位置
self._top = None
# 判空
def is_empty(self):
return self._top is None
# 入栈
def push(self, elem):
node = Node(elem)
node.next = self._top
self._top = node
# 出栈
def pop(self):
if self._top is None:
raise StackError('stack is empty')
p = self._top
self._top = p.next
return p.value
# 查看栈顶元素值
def top(self):
if self._top is None:
raise StackError('stack is empty')
return self._top .value
队列的顺序存储结构:
# 队列异常
class QueueError(Exception):
pass
# 完成队列操作
class SQueue:
def __init__(self):
self._elems = [] # 使用列表存储队列数据
# 判空
def is_empty(self):
return self._elems == []
# 入队
def enqueue(self, elem):
self._elems.append(elem)
# 出队
def dequeue(self):
if not self._elems:
raise QueueError("Queue is empty")
return self._elems.pop(0)
队列的链式存储结构(链表尾添加元素为入队,头删除为出队):
# 队列异常
class QueueError(Exception):
pass
# 创建结点类
class Node:
def __init__(self, value):
self.value = value
self.next = None
# 头(front)指向的是队头的前一个,尾(rear)指向的是最后一个
# 头 = 尾 时为空
class LQueue:
def __init__(self):
self.front = self.rear = Node(None)
# 判空
def is_empty(self):
return self.front is self.rear
# 入队
def enqueue(self, elem):
self.rear.next = Node(elem)
self.rear = self.rear.next
# 出队
def dequeue(self):
if self.front == self.rear:
raise QueueError("Queue is empty")
self.front = self.front.next
return self.front.value
# 清空
def clear(self):
self.front = self.rear
补充:用两个栈实现队列
stack1=[]
stack2=[]
# 入栈
def push(val):
stack1.append(val)
# 出栈
def pop():
if stack2 == []:
while stack1 != []:
stack2.append(stack1.pop())
return stack2.pop()
遍历:沿某条搜索路径周游二叉树,对树中的每一个节点访问一次且仅访问一次。
先序遍历:先访问树根,再访问左子树,最后访问右子树
中序遍历:先访问左子树,再访问树根,最后访问右子树
后序遍历:先访问左子树,再访问右子树,最后访问树根
层次遍历:从根节点开始,逐层从左向右进行遍历
重要代码:
from collections import deque
# 根节点
class TreeNode:
def __init__(self, data):
self.data = data
self.lchild = None
self.rchild = None
# 二叉树类
class BiTree:
def __init__(self, root):
self.root = root
# 判空
def is_empty(self):
if self.root is None:
return True
else:
return False
# 前序遍历
def pre_order(self, root):
if root is None:
return
print(root.data, end="")
self.pre_order(root.lchild)
self.pre_order(root.rchild)
# 中序遍历
def in_order(self, root):
if root is None:
return
self.in_order(root.lchild)
print(root.data, end="")
self.in_order(root.rchild)
# 后序遍历
def post_order(self, root):
if root is None:
return
self.post_order(root.lchild)
self.post_order(root.rchild)
print(root.data, end=" ")
# 层次遍历(队列思想)
def level_order(self, root):
q = deque()
q.append(root)
while len(q) > 0:
x = q.popleft()
print(x.data, end="")
if x.lchild:
q.append(x.lchild)
if x.rchild:
q.append(x.rchild)
已知前序遍历和中序遍历,重建二叉树:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
if not pre or not tin:
return None
root=TreeNode(pre.pop(0))
index=tin.index(root.val)
root.left=self.reConstructBinaryTree(pre,tin[:index])
root.right=self.reConstructBinaryTree(pre,tin[index+1:])
return root
补充面试题:
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
class Solution:
def GetNext(self, pNode):
# write code here
if pNode.right:# 如果有右子树,找最左边的叶子结点
p=pNode.right
while p.left:
p=p.left
return p
else:# 如果没有右子树,如果节点是父节点的左子节点,那么它的下一个节点是父节点
while pNode.next:
if pNode.next.left==pNode:
return pNode.next
pNode=pNode.next
return