class Node { public int data; public Node left,right; public Node(int data) { this.data = data; left = null; right = null; } } class BinaryTreeImp { Node root; static int count = 0; public BinaryTreeImp() { root = null; } public Node addNode(int data) { Node newNode = new Node(data); if (root == null) { root = newNode; } count++; return newNode; } public void insertNode(Node root,Node newNode ) { Node temp; temp = root; if (newNode.data < temp.data) { if (temp.left == null) { temp.left = newNode; } else { temp = temp.left; insertNode(temp,newNode); } } else if (newNode.data > temp.data) { if (temp.right == null) { temp.right = newNode; } else { temp = temp.right; insertNode(temp,newNode); } } } public void displayTree(Node root) { Node temp; temp = root; if (temp == null) return; displayTree(temp.left); System.Console.Write(temp.data + " "); displayTree(temp.right); } static void Main(string[] args) { BinaryTreeImp btObj = new BinaryTreeImp(); Node iniRoot= btObj.addNode(5); btObj.insertNode(btObj.root,iniRoot); btObj.insertNode(btObj.root,btObj.addNode(6)); btObj.insertNode(btObj.root,btObj.addNode(10)); btObj.insertNode(btObj.root,btObj.addNode(2)); btObj.insertNode(btObj.root,btObj.addNode(3)); btObj.displayTree(btObj.root); System.Console.WriteLine("The sum of nodes are " + count); Console.ReadLine(); } }
这是实现的代码.代码工作正常,但如果在displayTree函数中,我替换它
public void displayTree(Node root) { Node temp; temp = root; while(temp!=null) { displayTree(temp.left); System.Console.Write(temp.data + " "); displayTree(temp.right); } }
导致无限循环.我不明白是什么导致了这一点.我想知道是否有更好的方法在C#中实现BST.
解决方法
我不确定你为什么需要这个循环,但回答你的问题:
while(temp!=null) { displayTree(temp.left); System.Console.Write(temp.data + " "); displayTree(temp.right); }
此代码检查temp是否为null,但它永远不会变为null,因为在循环内部,您只对temp的叶子起作用.这就是为什么你有一个无限循环.