首页 > 编程语言 > 详细

Python用非递归实现二叉树中序遍历

时间:2021-09-08 20:57:04      阅读:38      评论:0      收藏: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

Python用非递归实现二叉树中序遍历

原文:https://www.cnblogs.com/chenguopa/p/15239983.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!