1. 构成二叉树如下图
5.第九章 树--9.3 二叉树遍历(3)

2.中序遍历:打印所有的元素包括当前节点

下面通过没一个结点的详细执行过程,来进行说名中序遍历是如何实现打印顺序的。请看下面图片:

5.第九章 树--9.3 二叉树遍历(3)
(图1)
5.第九章 树--9.3 二叉树遍历(3)
(图2)
5.第九章 树--9.3 二叉树遍历(3)
(图3)
5.第九章 树--9.3 二叉树遍历(3)
(图4)
执行完图4,到这里最先打印5,
执行图3,然后会到第三次调用,打印7,

5.第九章 树--9.3 二叉树遍历(3)

(图5)

5.第九章 树--9.3 二叉树遍历(3)

(图6)

打印3完成。
(图3执行完成)
接着执行图2中的打印:打印出9

5.第九章 树--9.3 二叉树遍历(3)

(图7)

接着执行打印出1
接着执行图1,打印出8

5.第九章 树--9.3 二叉树遍历(3)

(图8)


接着

5.第九章 树--9.3 二叉树遍历(3)

(图9)

打印出4,
打印出6

5.第九章 树--9.3 二叉树遍历(3)

(图10)

打印出2.
整个执行打印完成。
3.前序遍历和后序遍历,这两个个过程和中序遍历非常很相似。

4.代码实现
//    1.中序遍历:打印所有的元素包括当前节点
       public void inorderPrint(){
             if(left != null){
                   left.inorderPrint();
            }
            System. out.println(data );
             if(right != null){
                   right.inorderPrint();
            }
      }
                                           
//    2.前序遍历:打印所有的元素包括当前节点
       public void priorderPrint(){
            System. out.println(data );
             if(left != null){
                   left.priorderPrint();
            }
             if(right != null){
                   right.priorderPrint();
            }
      }
                                           
//    3.后序遍历:打印所有的元素包括当前节点
       public void postorderPrint(){
             if(left != null){
                   left.postorderPrint();
            }
             if(right != null){
                   right.postorderPrint();
            }
            System. out.println(data );
      }



One never notices what has been done;one can only see what remains to be done. ——Marie Curie

切不要注意已经做了哪些,而只能去考虑还有哪些有待去做。——居里夫人




转载于:https://blog.51cto.com/2008jiangning/1311248

相关文章:

  • 2022-12-23
  • 2021-05-14
  • 2021-11-27
猜你喜欢
  • 2021-11-27
  • 2022-01-03
  • 2021-04-22
  • 2022-12-23
  • 2021-08-19
  • 2022-02-20
  • 2022-12-23
相关资源
相似解决方案