ITPub博客

首页 > 应用开发 > Python > 刷题系列 - Python用非递归实现二叉树中序遍历

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

原创 Python 作者:张国平 时间:2020-01-16 22:56:24 0 删除 编辑

刷题没事会上瘾,继续做了非递归中序遍历。

中序遍历其实和就是先找到最左边节点,然后是其上级节点,再到上级节点的右边节点。

比如下面的中序遍历结果就是 DBEAFC



非递归实现逻辑,我想的这个比较笨。就是用一个队列做栈,先按照左边遍历压入栈中;当到左边叶子节点时候,读取并删除关联;推出栈回到上一级节点,如果上级节点没有右节点,则读取继续删除;如果有,则遍历右节点;为了防止右边遍历返回时候再次读取父节点;要记录下上次被推出节点,如果是右节点,则不读取父节点信息。

代码写的很难看,不去雕琢了,见笑。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        traversalList = []
        nodeList = []  
        # similar as Preorder traversal, the only change is that the value of node is recored when the node doesn't have left sub-node; new object removedNode as popped node, if a node's right sub-node is removedNode, then it should be popped both.
        if root != None:
            nodeList.append(root)
            currentNode = root
            removedNode = None
            while nodeList != []:
                if currentNode.left != None:
                    currentNode = currentNode.left
                    nodeList.append(currentNode)
                elif currentNode.right == None or currentNode.right == removedNode:
                    if currentNode.right == None:
                        traversalList.append(currentNode.val)
                    removedNode = nodeList.pop()
                    if nodeList!= []:
                        currentNode = nodeList[-1]
                        currentNode.left = None
                elif currentNode.right !=None:
                    traversalList.append(currentNode.val)
                    currentNode = currentNode.right
                    nodeList.append(currentNode)
                        
        return traversalList


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/22259926/viewspace-2673709/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
SAP 金融风险管理产品专家

注册时间:2009-08-05

  • 博文量
    229
  • 访问量
    635965