二叉树的遍历(python)
BEGIN:
class TreeNode: ''' 树节点 ''' def __init__(self,x): self.val = x self.left = None self.right = None def preTraversal(head): ''' 先根遍历 :param head: :return: ''' if not head: return print(head.val) preTraversal(head.left) preTraversal(head.right) def midTraversal(head): ''' 中根遍历 :param head: :return: ''' if not head: return midTraversal(head.left) print(head.val) midTraversal(head.right) def postTraversal(head): ''' 后根遍历 :param head: :return: ''' if not head: return postTraversal(head.left) postTraversal(head.right) print(head.val) """ 树结构: A B C D E F G 先根遍历:ABDECFG 中根遍历:DBEAFCG 后根遍历:DEBFGCA """ A, B, C, D, E, F, G = [TreeNode(x) for x in 'abcdefg'] A.left = B A.right = C B.left = D B.right = E C.left = F C.right = G head = A print("preTraversal>>>") preTraversal(head) print("midTraversal>>>") midTraversal(head) print("postTraversal>>>") postTraversal(head)
END.
勇气,不过就是人在无路可退时那最后的孤注一掷。