树遍历的新方式

之前写二叉树遍历都有两种方式,递归和迭代。

递归的代码非常简写好写,但是时间复杂度和空间复杂度总是不能让我们满意,迭代呢,处理的条件总是极为复杂,尤其是后序遍历,真的很恶心,在刷leetcode的时候,看到题解里有一道非常不错的方法,既能够使用栈减少空间复杂度,又能够简洁明了,统一前序遍历,后序遍历,中序遍历的算法。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        white,gray = 0,1
        stack=[(white,root)]
        res = []
        while len(stack):
            color,node = stack.pop(-1)
            if not node:
                continue
            if color == white:
                stack.append((white, node.right))
                stack.append((gray, node))
                stack.append((white, node.left))
            else:
                res.append(node.val)
        return res

            
发布了32 篇原创文章 · 获赞 6 · 访问量 9296

猜你喜欢

转载自blog.csdn.net/ningmengccccc/article/details/103441988