二叉树的后序遍历(非递归方法)

二叉树的后序遍历的话,利用stack进行非递归遍历,要先访问每个节点的左子树,在访问右子树,然后访问自身,

stack 一直循环,当栈顶节点(cur)的左右子树都是None的时候,

        或者当pre节点不是None的时候,同时pre和cur节点的左右子节点中的一个相等的时候

        可以出栈并访问

# 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 postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if root ==None:
            return []
        stack=[root]
        pre=None
        result=[]
        while (len(stack)!=0):
            cur =stack[-1]
            if ((cur.left ==None and cur.right==None) or (pre!=None and (pre==cur.left or  pre== cur.right))):
                
                cur=stack.pop()
                result.append(cur.val)
                pre=cur
            else:
                if cur.right!=None:
                    stack.append(cur.right)
                if cur.left!=None:
                    stack.append(cur.left)
        return result

猜你喜欢

转载自www.cnblogs.com/hit-joseph/p/9452497.html