码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-08-10 01:27:04      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:[]   return   order   post   nod   tor   init   访问   非递归遍历   

二叉树的后序遍历的话,利用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

 

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

标签:[]   return   order   post   nod   tor   init   访问   非递归遍历   

原文地址:https://www.cnblogs.com/hit-joseph/p/9452497.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!