树结构的三种遍历方式

前序遍历:
中序遍历:
后序遍历:

  1. /*
  2. 创建前序遍历的方法。
  3. */
  4. public void prelist() {
  5. //输出当前节点
  6. System.out.println(this);
  7. //判断当前节点的左节点是否为空,不为空则递归前序遍历
  8. if (this.left!=null){
  9. this.left.prelist();
  10. }
  11. //判断当前节点的右节点是否为空,不为空则递归前序遍历
  12. if (this.right!=null){
  13. this.right.prelist();
  14. }
  15. }
  16. /*
  17. 创建中序遍历的方法
  18. */
  19. public void midlist() {
  20. //首先判断当前节点的左节点是否为空,不为空则递归中序遍历
  21. if (this.left!=null){
  22. this.left. midlist();
  23. }
  24. //输出当前节点
  25. System.out.println(this);
  26. //回溯,判断当前节点的右节点是否为空,不为空则递归中序遍历
  27. if (this.right!=null){
  28. this.right.midlist();
  29. }
  30. }
  31. /*
  32. 遍历后续遍历的方法
  33. */
  34. public void postlist(){
  35. //首先判断当前节点的左节点是否为空,不为空则递归中序遍历
  36. if (this.left!=null){
  37. this.left. postlist();
  38. }
  39. //判断当前节点的右节点是否为空,不为空则递归中序遍历
  40. if (this.right!=null){
  41. this.right.postlist();
  42. }
  43. //最后输出当前节点
  44. System.out.println(this);
  45. }