遍历如图二叉树:
1.先序遍历
(1)先访问根结点
(2)再遍历左子树
(2)最后遍历右子树
private static void PreOrder(BiTree root, Action<BiTree> visit)
{
if (root == null) return;
visit(root);
PreOrder(LeftChild(root), visit);
PreOrder(RightChild(root), visit);
}
输出结果为:0,1,3,5,6,4,2
2.中序遍历
(1)先遍历左子树
(2)再访问根结点
(3)最后遍历右子树
private static void InOrder(BiTree root, Action<BiTree> visit)
{
if (root == null) return;
InOrder(LeftChild(root), visit);
visit(root);
InOrder(RightChild(root), visit);
}
输出结果为:1,6,5,3,4,0,2
3.后序遍历
(1)先遍历左子树
(2)再遍历右子树
(3)最后访问根结点
private static void PostOrder(BiTree root, Action<BiTree> visit)
{
if (root == null) return;
PostOrder(LeftChild(root), visit);
PostOrder(RightChild(root), visit);
visit(root);
}
输出结果为:6,5,4,3,1,2,0