【转载】二叉树的前序、中序、后序遍历 python

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

你可能感兴趣的:(二叉树,后序中序求前序,二叉树遍历)