PYTHON经典算法-二叉树的后序遍历

二叉树的后序遍历

问题描述

给出一个二叉树,返回其节点值的后序遍历

问题示例

给出一个二叉树{1,x,2,3}其中x表示空。后序遍历为[3,2,1]
PYTHON经典算法-二叉树的后序遍历

这个图怎么画的呢?答案

需要注意的地方是:binarytree.gvpr需要去下载。放在和.dot文件同一个目录

tree.dot文件为
graph g {
  A--NULL[style=invis]; 
  A--B;
  B--C; 
  B--D[style=invis];
  A[shape=circle, label="1"];
  B[shape=circle, label="2"];
  C[shape=circle, label="3"];
  D[style=invis];
  NULL[style=invis];
}

代码实现

class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
class Solution:
    result = []
    def traverse(self, root):
        if root is None:
            return
        self.traverse(root.left)
        self.traverse(root.right)
        self.results.append(root.val)
    def postorderTraversal(self, root):
        self.results = []
        self.traverse(root)
        return self.results
        # 
def printTree(root):
    res = []
    if root is None:
        print(res)
    queue = []
    queue.append(root)
    while len(queue) != 0:
        tmp = []
        length = len(queue)
        for i in range(length):
            r = queue.pop(0)
            if r.left is not None:
                queue.append(r.left)
            if r.right is not None:
                queue.append(r.right)
            tmp.append(r.val)
        res.append(tmp)
    print(res)
if __name__ == '__main__':
    root = TreeNode(1)
    root.right = TreeNode(2)
    root.right.left = TreeNode(3)
    print("原始二叉树为")
    printTree(root)
    solution = Solution()
    print("后序遍历的结果为", solution.postorderTraversal(root))

运行结果

PYTHON经典算法-二叉树的后序遍历