class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
#前序
def preorder(self,root,ans=[]):
if root!=None:
ans.append(root.val)
if root.left:
self.preorder(root.left,ans)
if root.right:
self.preorder(root.right,ans)
return ans
#中序
def inorder(self,root,ans=[]):
# if root.left==None and root.right==None:
# ans.append(root.val)
# return
if root.left:
self.inorder(root.left,ans)
ans.append(root.val)
if root.right:
self.inorder(root.right,ans)
return ans
#后序
def postorder(self,root,ans=[]):
if root.left:
self.postorder(root.left,ans)
if root.right:
self.postorder(root.right,ans)
ans.append(root.val)
return ans
【转载】二叉树的前序、中序、后序遍历 python
最新推荐文章于 2023-12-20 13:33:39 发布