二叉树最小深度
普遍用层序遍历和先序遍历
也就是广度优先和深度优先
这里需要用到 copy
用法:
copy() 这个就和普通的 a = b 是一样的 当a 变了 b 也会随之改变
copy.deepcopy() 当a 变了 b 也会随之改变
# 创建节点 class Node: # 构造函数 def __init__(self ,elem): self.data = elem self.lchild = None self.rchild = None # 创建树 class Tree: def __init__(self): self.root = None self.queue = [] def add(self ,elem): #print(self.queue) node = Node(elem) if self.root == None: self.root = node self.queue.append(self.root) else: parent = self.queue[0] ############################################ #补充 非完全二叉树 #print(parent.data) if elem == None: if parent.lchild == None: parent.lchild = -1 return if parent.rchild == None: parent.rchild = -1 self.queue.pop(0) return ########################################### if parent.lchild == None: parent.lchild = node self.queue.append(node) else: parent.rchild = node self.queue.append(node) #print(parent.data) #print(node.data) self.queue.pop(0) # 层序遍历 def level_queue(self): #print(self.queue) root = self.root q = [root] c = 0 while q != []: parent = q.pop(0) if parent == None: print(None) continue c += 1 #print(parent.data) if parent.lchild == -1: q.append(None) if parent.rchild == -1: q.append(None) if parent.lchild == -1 and parent.rchild == -1: break if parent.lchild != None and parent.lchild != -1: q.append(parent.lchild) if parent.rchild != None and parent.rchild != -1: q.append(parent.rchild) tot = 0 for i in range(100): tot += pow(2,i) if c <= tot: print(i + 1) break def min_deepth(self,root): if root == None: return cur = [root] sec = [] c = 0 flag = 0 import copy while True: while cur != []: parent = cur.pop(0) if parent.lchild == -1 and parent == -1: flag = 1 break if parent.lchild == None and parent == None: flag = 1 break if parent.lchild != -1 and parent.lchild != None: sec.append(parent.lchild) if parent.rchild != -1 and parent.rchild != None: sec.append(parent.rchild) c += 1 if flag == 1: break cur = copy.deepcopy(sec) sec = [] if cur == [] and sec == []: break return c # traverse 先序遍历 def front_traverse(self ,parent): if parent == None: return print(parent.data) if parent.lchild != -1: self.front_traverse(parent.lchild) else: print("None") if parent.rchild != -1: self.front_traverse(parent.rchild) else: print("None") #中序遍历 def mid_traverse(self ,parent): if parent == None: return self.mid_traverse(parent.lchild) print(parent.data) self.mid_traverse(parent.rchild) # 后序遍历 def later_traverse(self, parent): if parent == None: return self.later_traverse(parent.lchild) self.later_traverse(parent.rchild) print(parent.data) # 类名(参数) -》创建对象 tree = Tree() f1 = [3,9,20,None,None,15,7] pts = [5,2,8,1,4,7,None,None,None,3] pts2 = [7,2,8,1,4,None,None,None,None,3,5] for i in pts: tree.add(i) tree.min_deepth(tree.root) print(tree.c)