当前位置:   article > 正文

二叉树简单模拟

二叉树简单模拟

  1. package com.test.utils;
  2. /**
  3. * 二叉树模拟类
  4. */
  5. public class Tree {
  6. // 根节点
  7. private TreeNode rootNode = new TreeNode(null, null, null);
  8. /**
  9. * 添加数据
  10. */
  11. public TreeNode add(Long data) {
  12. TreeNode node = new TreeNode(data, null, null);
  13. TreeNode currentNode = rootNode;
  14. if (null != currentNode.data) {
  15. while (true) {
  16. TreeNode parentNode = currentNode;
  17. if (data < parentNode.getData()) {
  18. currentNode = currentNode.getLeftChildNode();
  19. if (null == currentNode) {
  20. parentNode.setLeftChildNode(node);
  21. return node;
  22. }
  23. } else {
  24. currentNode = currentNode.getRightChildNode();
  25. if (null == currentNode) {
  26. parentNode.setRightChildtNode(node);
  27. return node;
  28. }
  29. }
  30. }
  31. } else {
  32. rootNode.data = data;
  33. return node;
  34. }
  35. }
  36. /**
  37. * 查找节点
  38. */
  39. public TreeNode find(long data) {
  40. TreeNode currentNode = rootNode;
  41. while (null != currentNode && data != currentNode.getData()) {
  42. if (data < currentNode.getData()) {
  43. currentNode = currentNode.getLeftChildNode();
  44. } else {
  45. currentNode = currentNode.getRightChildNode();
  46. }
  47. }
  48. return currentNode;
  49. }
  50. /**
  51. * 前序遍历
  52. */
  53. public void frontOrder(TreeNode node) {
  54. if (null != node) {
  55. System.out.println(node.data);
  56. frontOrder(node.getLeftChildNode());
  57. frontOrder(node.getRightChildNode());
  58. }
  59. }
  60. /**
  61. * 中序遍历
  62. */
  63. public void inOrder(TreeNode node) {
  64. if (null != node) {
  65. inOrder(node.getLeftChildNode());
  66. System.out.println(node.data);
  67. inOrder(node.getRightChildNode());
  68. }
  69. }
  70. public TreeNode getRootNode() {
  71. return rootNode;
  72. }
  73. /**
  74. * 二叉树节点对象
  75. */
  76. public class TreeNode {
  77. private Long data; // 数据域
  78. private TreeNode leftChildNode; // 左子节点
  79. private TreeNode righttChildNode;// 右子节点
  80. public TreeNode(Long data, TreeNode leftChildNode, TreeNode righChildtNode) {
  81. super();
  82. this.data = data;
  83. this.leftChildNode = leftChildNode;
  84. this.righttChildNode = righChildtNode;
  85. }
  86. public Long getData() {
  87. return data;
  88. }
  89. public TreeNode getLeftChildNode() {
  90. return leftChildNode;
  91. }
  92. public void setLeftChildNode(TreeNode leftChildNode) {
  93. this.leftChildNode = leftChildNode;
  94. }
  95. public TreeNode getRightChildNode() {
  96. return righttChildNode;
  97. }
  98. public void setRightChildtNode(TreeNode rightChildtNode) {
  99. this.righttChildNode = rightChildtNode;
  100. }
  101. }
  102. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/1015420
推荐阅读
相关标签
  

闽ICP备14008679号