WC138实现二叉树先序,中序和后序遍历

描述
分别按照二叉树先序,中序和后序打印所有的节点。
示例1
输入:
{1,2,3}
返回值:
[[1,2,3],[2,1,3],[2,3,1]]

有递归和非递归方法:

递归

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

#
# 
# @param root TreeNode类 the root of binary tree
# @return int整型二维数组
#
class Solution:
    def __init__(self):
      self.pre_re = []
      self.mid_re = []
      self.pos_re = []
    def pre(self,root):
      if root==None:
        return 
      self.pre_re.append(root.val)
      if root.left: self.pre(root.left)
      if root.right:self.pre(root.right)
    def mid(self,root):
      if root==None:
        return
      if root.left: self.mid(root.left)
      self.mid_re.append(root.val)
      if root.right :self.mid(root.right)
    def post(self,root):
      if root==None: return
      if root.left:self.post(root.left)
      if root.right:self.post(root.right)
      self.pos_re.append(root.val)
      
    def threeOrders(self , root ):
      self.pre(root)
      self.mid(root)
      self.post(root)
      re = [self.pre_re,self.mid_re,self.pos_re]
      print(re)
      return re
        # write code here

非递归

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

#
# 
# @param root TreeNode类 the root of binary tree
# @return int整型二维数组
#
class Solution:
    def __init__(self):
      self.pre_re = []
      self.mid_re = []
      self.pos_re = []
    def pre(self,root):
      visited =[]
      val =[]
      while root or visited:
        while root:
          visited.append(root)
          val.append(root.val)
          root = root.left
        if visited:
          root = visited.pop()
          root = root.right
      self.pre_re = val
      
    def mid(self,root):
      visited = []
      val =[]
      while root or visited:
        while root:
          visited.append(root)
          root = root.left
        if visited:
          root = visited.pop()
          val.append(root.val)
          root = root.right
      self.mid_re = val
    def post(self,root):
      visited = [root]
      val = []
      while visited:
        node = visited.pop()
        val.append(node.val)
        if node.left:
          visited.append(node.left)
        if node.right:
          visited.append(node.right)
      self.pos_re = val[::-1]
      
    def threeOrders(self , root ):
      self.pre(root)
      self.mid(root)
      self.post(root)
      re = [self.pre_re,self.mid_re,self.pos_re]
      print(re)
      return re
        # write code here

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值