# 数据结构-树以及深度、广度优先遍历（递归和非递归，python实现）

## 树

# 定义一个普通的树类
class Tree:
def __init__(self, data):
self.data = data
self.children = []

def get(self):
return self.data

def set(self):
return self.data

self.children.append(child)

def getChildren(self):
return self.children


# 初始化一个树
tree = Tree(0)
# 添加三个子节点
children = tree.getChildren()
# 每个子节点添加两个子节点


OK，我们的树已经实例化好了，我们先来对它分别采用递归和非递归的方式进行广度优先遍历:

### 广度优先遍历

# 用以实现广度优先遍历
class Queue():
def __init__(self):
self.__list = list()

def isEmpty(self):
return self.__list == []

def push(self, data):
self.__list.append(data)

def pop(self):
if self.isEmpty():
return False
return self.__list.pop(0)


#### 用队列实现广度优先遍历

# 广度优先遍历
queue = Queue()
queue.push(tree)
result = []
while not queue.isEmpty():
node = queue.pop()
result.append(node.data)
for c in node.getChildren():
queue.push(c)
return result


print(breadthFirst(tree))


#### 递归实现广度优先遍历

# 递归方式实现广度优先遍历

if type(gen) == Tree:
gen = [gen]
result.append(gen[index].data)

children = gen[index].getChildren()

nextGen += children
if index == len(gen)-1:
if nextGen == []:
return
else:
gen = nextGen
nextGen = []
index = 0
else:
index += 1

return result


print(breadthFirstByRecursion(tree))


### 深度优先遍历

# 用以实现深度优先遍历
class Stack():
def __init__(self):
self.__list = list()

def isEmpty(self):
return self.__list == []

def push(self, data):
self.__list.append(data)

def pop(self):
if self.isEmpty():
return False
return self.__list.pop()


#### 利用堆栈实现深度优先遍历

# 深度优先遍历
def depthFirst(tree):
stack = Stack()
stack.push(tree)
result = []
while not stack.isEmpty():
node = stack.pop()
result.append(node.data)
children = node.getChildren()
children = reversed(children)
for c in children:
stack.push(c)
return result


# 深度优先遍历
print(depthFirst(tree))


#### 递归实现深度优先遍历

# 递归方式实现深度优先遍历
def depthFirstByRecursion(tree, result=[]):
result.append(tree.data)
children = tree.getChildren()
for c in children:
depthFirstByRecursion(c, result)
return result


print(depthFirstByRecursion(tree))


posted @ 2019-07-18 01:08  目标进大厂的柳乘风  阅读(1887)  评论(0编辑  收藏