java中二叉搜索树的加法

vsikbqxv  于 2021-06-27  发布在  Java
关注(0)|答案(2)|浏览(353)

我有一段代码,用于在java中向二进制搜索树插入节点,如:

  1. public class BST {
  2. private Node head;
  3. public BST() {
  4. this.head = null;
  5. }
  6. public void add(int data, Node head) {
  7. if (head == null)
  8. head = new Node(data);
  9. else {
  10. if (data < head.data)
  11. add(data, head.left);
  12. else
  13. add(data, head.right);
  14. }
  15. }
  16. public void add(int data) {
  17. add(data, this.head);
  18. }
  19. public void preOrder(Node head) {
  20. if (head != null) {
  21. System.out.print(head.data + " ");
  22. preOrder(head.left);
  23. preOrder(head.right);
  24. }
  25. }
  26. public void preOrder() {
  27. preOrder(this.head);
  28. }
  29. public static void main(String[] args) {
  30. BST bst = new BST();
  31. for (int i = 0; i < 10; i++) {
  32. bst.add(i);
  33. }
  34. bst.preOrder();
  35. }
  36. }

为什么我运行程序时不打印我的信息?谢谢你回答我的问题!!

cnh2zyt3

cnh2zyt31#

当递归返回时,不更新左/右指针。此外,局部变量head与示例变量不同。因此,当方法返回时,您创建的新节点将被丢弃。
这里有一个方法。
二等兵 add 方法返回更新的节点,该节点在递归返回时被(重新)分配。

  1. private Node add(int data, Node node) {
  2. if (node == null)
  3. return new Node(data);
  4. else {
  5. if (data < node.data)
  6. node.left = add(data, node.left);
  7. else
  8. node.right = add(data, node.right);
  9. }
  10. return node;
  11. }
  12. public void add(int data) {
  13. this.head = add(data, this.head);
  14. }
展开查看全部
b1payxdu

b1payxdu2#

还有一个选择:

  1. public void add(int data) {
  2. if(head == null) {
  3. this.head = new Node(data);
  4. }
  5. else {
  6. add(data, this.head);
  7. }
  8. }
  9. public void add(int data, Node node) {
  10. if(data < node.data) {
  11. if(node.left == null) {
  12. node.left = new Node(data);
  13. }
  14. else {
  15. add(data, node.left);
  16. }
  17. }
  18. else {
  19. if(node.right == null) {
  20. node.right = new Node(data);
  21. }
  22. else {
  23. add(data, node.right);
  24. }
  25. }
  26. }
展开查看全部

相关问题