class TreeNode(): def __init__(self,val = 0,left = None,right = None): self.val = val self.left = left self.right = right class Solution: def inorderTraversal(self,root): def inner_find(node): while node: node_stack.append(node) node = node.left res = []; node_stack = [] inner_find(root) #找到所有左边的节点 while node_stack: temp = node_stack.pop() res.append(temp.val) inner_find(temp.right) #找到所有右边的节点 return res def forwardTraversal(self,root): res = []; node_stack = [] node_stack.append(root) while node_stack: temp = node_stack.pop() res.append(temp.val) if temp.right: node_stack.append(temp.right) if temp.left: node_stack.append(temp.left) return res def behindTraversal(self,root): def inner_find(node): while node: node_stack.append(node) node = node.left res = []; node_stack = [];pre = None inner_find(root) #找到所有左边的节点 while node_stack: flage = node_stack[-1] if flage.right == None or flage.right ==pre: temp = node_stack.pop() res.append(temp.val) pre = temp else: inner_find(flage.right) return res
'''
前序遍历最简单
中序遍历和后序遍历有相同点,都是先找最左边的节点,不同的是中序遍历是找完最左边节点之后就直接取值,再去找右边的节点,再找右边节点;
而后续遍历需要增加一些苛刻的条件才可以取值,这个条件不满足就不能取值,而是因为继续找右边的节点。
'''
if __name__ == '__main__': #构建一棵树 #1、先创建点 A,B,C,D,E,F,G,H,I = [TreeNode(x) for x in 'ABCDEFGHI'] #2、再创建树的依赖关系 A.left,A.right = B,C B.right = D C.left,C.right = E,F E.left = G F.left,F.right = H,I #3、对树进行中序遍历,即 B,D,A,G,E,C,H,F,I print(Solution().inorderTraversal(A)) #4、对数进行前序遍历,即A,B,D,C,E,G,F,H,I print(Solution().forwardTraversal(A)) #5、对数进行后序遍历,即D,B,G,E,H,I,F,C,A print(Solution().behindTraversal(A))