話很少說,直接上代碼app
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
童鞋們記得,不論是編寫仍是利用前序、中序、後序遍歷,記得在根節點順序的位置搞事情。post