二叉树用栈实现前序中序后序--python

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

class Solution:
    def preorderTraversal(self, root):
        """
        前序遍历,先遍历根节点,如果右子树存在把右子树根节点放入栈,最后把左子树放入栈
        """
        result = []
        if root == None:
            return result
        nodeStack = []
        nodeStack.append(root)
        while len(nodeStack) !=0 :
            node = nodeStack.pop()
            result.append(node.val)
            if node.right != None:
                nodeStack.append(node.right)
            if node.left != None:
                nodeStack.append(node.left)

        return result

    def inorderTraversal(self, root):
        '''
        中序遍历,寻找左子树为空的节点遍历的节点都入栈,直到左子树是叶子节点,
        节点出栈,并访问该节点的右子树如果存在入栈,并寻找该节点的左子树,如果
        不存在左子树,栈顶元素出栈
        '''
        res = []  ##存放节点的值 
        stack = [] ###存放节点
        while root or stack:
            if root:
                stack.append(root)
                root = root.left
            else:
                root = stack.pop()
                res.append(root.val)
                root = root.right
        return res
    
    
   '''
   后序遍历可以是根右左生成序列的倒序排序
   '''
   def postorderTraversal(self, root):
        result = []
        if root == None:
            return result
        nodeStack = []
        nodeStack.append(root)
        while len(nodeStack) != 0:
            node = nodeStack.pop()
            result.append(node.val)

            if node.left != None:
                nodeStack.append(node.left)
            if node.right != None:
                nodeStack.append(node.right)

        print(result[::-1])
        return result[::-1]  # 反转后就是左右根

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值