二叉树的三种查找方式

前序查找、中序查找、后序查找

  1. //前序查找的方法
  2. public HeroNode preSearch(int id) {
  3. if (this.id == id) {
  4. return this;
  5. } else {
  6. //左节点遍历查找时,定义一个变量来判读是否找到。如果找到,就把该节点赋给result
  7. HeroNode resultNoede = null;
  8. if (this.left != null) {
  9. resultNoede = this.left.preSearch(id);
  10. }
  11. if (resultNoede != null) {
  12. return resultNoede;
  13. } else {
  14. if (this.right != null) {
  15. resultNoede = this.right.preSearch(id);
  16. }
  17. return resultNoede;
  18. }
  19. }
  20. }
  21. //中序查找
  22. public HeroNode midSearch(int id) {
  23. HeroNode resultNode = null;
  24. if (this.left != null) {
  25. resultNode = this.left.midSearch(id);
  26. }
  27. if (resultNode!=null) {
  28. return resultNode;
  29. } else {
  30. if (this.id == id) {
  31. return this;
  32. } else {
  33. if (this.right != null) {
  34. resultNode = this.right.midSearch(id);
  35. }
  36. return resultNode;
  37. }
  38. }
  39. }
  40. //后序查找
  41. public HeroNode postSearch(int id) {
  42. HeroNode resultNode = null;
  43. if (this.left != null) {
  44. resultNode = this.left.postSearch(id);
  45. }
  46. if (resultNode!=null) {
  47. return resultNode;
  48. } else {
  49. if (this.right != null) {
  50. resultNode = this.right.postSearch(id);
  51. }
  52. if (resultNode!=null) {
  53. return resultNode;
  54. } else {
  55. if (this.id == id) {
  56. return this;
  57. }
  58. return null;
  59. }
  60. }
  61. }