二叉树遍历的说明

使用前序,中序和后序对下面的二叉树进行遍历.
092_序_前序中序后序遍历二叉树图解 - 图1
092_序_前序中序后序遍历二叉树图解 - 图2

  • 前序遍历: 先输出父节点,再遍历左子树和右子树
  • 中序遍历: 先遍历左子树,再输出父节点,再遍历右子树
  • 后序遍历: 先遍历左子树,再遍历右子树,最后输出父节点
    小结: 看输出父节点的顺序,就确定是前序,中序还是后序

二叉树遍历应用实例(前序,中序,后序)
.
092_序_前序中序后序遍历二叉树图解 - 图3
要求如下:
前上图的 3号节点 “卢俊” , 增加一个左子节点 [5, 关胜]
使用前序,中序,后序遍历,请写出各自输出的顺序是什么?

  1. class HeroNode {
  2. private int no;
  3. private String name;
  4. private HeroNode leftNode;
  5. private HeroNode rightNode;
  6. public HeroNode(int hNo, String hName) {
  7. no = hNo;
  8. name = hName;
  9. }
  10. // 前序遍历
  11. public void preOrder() {
  12. System.out.println(this);//先输出父节点
  13. if (this.leftNode != null) {
  14. this.leftNode.preOrder();
  15. }
  16. if (this.rightNode != null) {
  17. this.rightNode.preOrder();
  18. }
  19. }
  1. class BinaryTree {
  2. private HeroNode root;
  3. public void setRoot(HeroNode root) {
  4. this.root = root;
  5. }
  6. // 前序遍历
  7. public void preOrder() {
  8. if (root != null) {
  9. root.preOrder();
  10. }
  11. }
  12. }