python非递归前序遍历二叉树_刷题系列 - Python用非递归实现二叉树前序遍历

刷刷题换换下脑子。

然后去一个刷题网站,从入门开始,没想到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 矩阵判断。这里就不细致研究了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值