BST引发的讨论

#include <stdio.h>
#include  <stdlib.h>
#define ElementType int
#define KeyType int
typedef struct node {
	ElementType key;
	struct node *leftChild, *rightChild;

} *BiTree, *BSTnode;

int BST_Insert(BiTree &T, KeyType k) {
	if (T == NULL) {
		/* code */
		T = (BiTree)malloc(sizeof(BSTnode));
		T->key = k;
		T->leftChild = T->rightChild = NULL;
		return 1;
	} else if(k == T->key) {
		return 0;
	} else if(k < T->key) {
		return BST_Insert(T->leftChild, k);
	} else {
		return BST_Insert(T->rightChild, k);
	}
}

void dfs(BiTree &T) {
	if (T == NULL) {
		return;
		/* code */
	}
	dfs(T->leftChild);
	printf("%d\n", T->key );
	dfs(T->rightChild);
}

int main(int argc, char const *argv[]) {
	BiTree root = NULL;
	BST_Insert(root, 14);
	BST_Insert(root, 1);
	BST_Insert(root, 15);
	BST_Insert(root, 2);
	BST_Insert(root, 0);
	return 0;
}

这是c的BST的插入与中序遍历代码,结果如下:

0
1
2
14
15

就是说没有什么大问题。然而仔细想一下,如果你用java去实现类似的操作,就会出现输出为空的情况:

/**
 * @author smi1e
 * Date 2019/10/24 23:08
 * Description
 */
public class BSTTest {
    static class BST {
        int data;
        BST lchild, rchild;
    }
    
    static int BSTInsert(BST T, int k) {
        if (T == null) {
            T = new BST();
            T.data = k;
            T.lchild = T.rchild = null;
            return 1;
        } else if (T.data == k) {
            return 0;
        } else if (k < T.data) {
            return BSTInsert(T.lchild, k);
        } else {
            return BSTInsert(T.rchild, k);
        }
    }

    static void dfs(BST T) {
        if (T == null) {
            return;
            /* code */
        }
        dfs(T.lchild);
        System.out.println(T.data);
        dfs(T.rchild);
    }

    public static void main(String[] args) {
        BST root = null;
        BSTInsert(root, 14);
        BSTInsert(root, 1);
        BSTInsert(root, 15);
        BSTInsert(root, 2);
        BSTInsert(root, 0);
        dfs(root);
    }

}

结果却是没有输出

从而产生应用传递与地址传递的争论~~~

其实c的&是直接传入内存所在的那一整块东西,去修改也就是内存的修改,而java传进去的是内存的引用,当引用为null时,根本就没有申请任何内存地址,所以也就没有值的出现了!

发布了31 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/sjs_caomei/article/details/102734294
BST