刷刷题换换下脑子。
然后去一个刷题网站,从入门开始,没想到python写多了,数据结构都忘了,第一个二叉树前序遍历就想了好久才写出来。这里记录下,也算记录。
二叉树前序遍历(Binary Tree Preorder Traversal), 前序遍历首先访问根结点然后遍历左子树,最后遍历右子树。
如下图所示,前序遍历结果:ABDECF
考虑了下,要创建两个队列,一个放遍历结果,一个做类似栈作用,把路过节点放入;如果当前节点左边节点存在,读取值并放入栈继续去下个左节点, 如果没有
左边节点则去右节点,同样操作;如果都没有,则栈弹出最后一个节点,删除关联,并把栈中上一个节点作为当前节点,相当于返回走。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
traversalList = []
nodeList = []
# add the first one to node list, and travel from left node first, then right; if a node without left #and righ sub-node, pop it from node list, then remove the link with parent node; traverlous finish as root list #is empty.
if root != None:
traversalList.append(root.val)
nodeList.append(root)
currentNode = root
while nodeList != []:
if currentNode.left != None:
currentNode = currentNode.left
traversalList.append(currentNode.val)
nodeList.append(currentNode)
elif currentNode.right != None:
currentNode = currentNode.right
traversalList.append(currentNode.val)
nodeList.append(currentNode)
else:
nodeList.pop()
if nodeList != []:
if nodeList[-1].right == currentNode:
nodeList[-1].right = None
elif nodeList[-1].left == currentNode:
nodeList[-1].left = None
currentNode = nodeList[-1]
return traversalList
通过后,运行时间只能一般,想想应该有更好的方法,比如使用NP.Array 矩阵判断。这里就不细致研究了