[关闭]
@XQF 2018-03-07T23:00:19.000000Z 字数 1450 阅读 889

如何实现二叉排序树?

数据结构与算法


二叉树的递归定义:二叉树或者是一棵空树,或者是一棵由根节点和左右子树组成,。,其中左右子树同样是一棵二叉树

二叉排序树的性质:

  1. 如果左子树不为空,那么左子树上所有结点的值均小于根结点的值
  2. 如果右子树不为空,那么右子树上所有结点的值均小于根结点的值
  3. 左右子树分别为二叉排序树

重要的是步骤非插入不可,。,。和链表一样,。用个指针。

  1. class TreeNode {
  2. int data;
  3. TreeNode left;
  4. TreeNode right;
  5. public TreeNode(int data) {
  6. this.data = data;
  7. this.left = null;
  8. this.right = null;
  9. }
  10. }
  11. class BinaryTree {
  12. TreeNode root;
  13. public BinaryTree() {
  14. root = null;
  15. }
  16. public void insert(int data) {
  17. TreeNode node = new TreeNode(data);
  18. if (root == null) {
  19. root = node;
  20. } else {
  21. TreeNode dummy = root;
  22. while (true) {
  23. if (node.data < dummy.data) {
  24. if (dummy.left == null) {
  25. dummy.left = node;
  26. return;
  27. }
  28. dummy = dummy.left;
  29. } else {
  30. if (dummy.right == null) {
  31. dummy.right = node;
  32. return;
  33. }
  34. dummy = dummy.right;
  35. }
  36. }
  37. }
  38. }
  39. public TreeNode create(int[] datas) {
  40. for (int i = 0; i < datas.length; i++) {
  41. insert(datas[i]);
  42. }
  43. return root;
  44. }
  45. public void inOrder(TreeNode root) {
  46. if (root != null) {
  47. inOrder(root.left);
  48. System.out.print(root.data + " ");
  49. inOrder(root.right);
  50. }
  51. }
  52. public void preOrder(TreeNode root) {
  53. if (root != null) {
  54. System.out.print(root.data + " ");
  55. preOrder(root.left);
  56. preOrder(root.right);
  57. }
  58. }
  59. public void postOrder(TreeNode root) {
  60. if (root != null) {
  61. postOrder(root.left);
  62. postOrder(root.right);
  63. System.out.print(root.data + " ");
  64. }
  65. }
  66. }
  67. public class Solution {
  68. public static void main(String[] args) {
  69. BinaryTree tree = new BinaryTree();
  70. int[] nums = {1, 3, 4, 5, 6, 4, 3, 2};
  71. System.out.print("中序:");
  72. TreeNode root = tree.create(nums);
  73. tree.inOrder(root);
  74. System.out.println();
  75. System.out.print("先序:");
  76. tree.preOrder(root);
  77. System.out.println();
  78. System.out.print("后序:");
  79. tree.postOrder(root);
  80. System.out.println();
  81. }
  82. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注