树总纲(To be continued)
递归:
1.前序,中序,后序:
def DFS(self,root):
if not root: return []
res = []
def helper(node):
if not node: return
res.append(node.val)
if node.left: helper(node.left)
if node.right: helper(node.right)
helper(root)
return res
2. 宽度遍历
def BFS(self,root):
if not root: return []
res = []
def helper(node,level):
if not node:
return
if len(res) == level:
res.append([])
res[level].append(node.val)
if node.left:
helper(node.left,level+1)
if node.right:
helper(node.right,level+1)
helper(root,0)
return res
迭代:
前序:
def frontSearch(self,root):
if not root: return []
res = []
stack = [root]
while stack:
node = stack.pop()
res.append(node.val)
if node.left: stack.append(node.left)
if node.right: stack.append(node.right)
return res
中序:
def midSearch(self,root):
if not root: return []
res = []
stack = []
while stack or root:
if root:
stack.append(root)
root = root.left
else:
root = stack.pop()
res.append(root.val)
root = root.right
return res
后序:
def backSearch(self,root):
if not root: return []
res = []
stack = [root]
while stack:
node = stack.pop()
res.append(node.val)
if node.left: stack.append(node.left)
if node.right: stack.append(node.right)
return res[::-1]
层序遍历:
def BFS(self,root):
if not root: return []
res = []
nodelist = [root]
while nodelist:
nextNodeList = []
vals =[]
for node in nodeList:
vals.append(node.val)
if node.left: nextNodeList.append(node.left)
if node.right: nextNodeList.append(node.right)
res.append(vals)
nodelist =[_ for _ in nextNodeList]
return res