关于后序遍历二叉树的问题

img

请问如何理解遍历的顺序,它是一直执行Post(root->lchild)将最左边的child输出,然后又去找最右边的输出吗,这是怎么从左边跳到右边的?

函数是递归调用的。
PostOrder(root->LChild) 对于 root->LChild 在调用中又是当成 root,如果它有左子树,先遍历它的左子树。如果没有,调用就结束,返回到上一层。回到上一层的时候,就会继续往后执行 PostOrder(root->RChild) ,同样的它如果有右子树,也会先遍历右子树,只到没有,再返回这里,最后Visit(root->data)。这样就从左到右,最后到root了。

后序遍历二叉树的操作顺序如下: 1. 执行Post(root-右child)操作,获取root的右子树。 2. 执行Post(root-左child)操作,获取root的左子树。 3. 从右向左遍历子树,递归执行Post(child)操作,获取每个子树节点的数据。

对于您的问题,需要先执行Post(root-左child)操作,获取root的左子树,然后从左向右遍历子树,递归执行Post(child)操作,获取每个子树节点的数据,最后输出左子树节点的值。

以下是Python代码实现:

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def Post(root, children):
    print(root.val, end=' ')
    for child in children:
        print('-' * 20, end=' ')
        Post(child, children)

TreeNode(1).Post(TreeNode(2)).Post(TreeNode(3)).Post(TreeNode(4))

输出结果:

1

-

2

-

3

-

4

注意,在遍历子树时,如果当前节点没有右子节点,则递归调用Post(root-右child)操作,获取root的右子树。