在学校的Java中,我被要求“在二进制树的预先遍历遍历中返回节点x之后访问的节点”。我已经创建了一个代码来按顺序列出所有节点,但我不确定如何打印单个节点。
我创建节点的第一个类是:
public class TreeNode {
int value; // The data in this node.
TreeNode left; // Pointer to the left subtree.
TreeNode right; // Pointer to the right subtree.
TreeNode parent; //Pointer to the parent of the node.
TreeNode(int value) {
this.value = value;
this.right = null;
this.left = null;
this.parent = null;
}
public void displayNode() { //Displays the value of the node.
System.out.println(value + " ");
}
然后我有了构建二叉树的类。它还按预先打印整个树:
public class BTree2 {
TreeNode root; // the first node in the tree
public boolean isEmpty() // true if no links
{
return root == null;
}
private TreeNode addRecursive(TreeNode current, int value) {
if (current == null) {
return new TreeNode(value);
}
if (value < current.value) {
current.left = addRecursive(current.left, value);
} else if (value > current.value) {
current.right = addRecursive(current.right, value);
} else {
// value already exists
return current;
}
return current;
}
public void add(int value) {
root = addRecursive(root, value);
}
void printPreorder(TreeNode node) {
if (node == null) {
return;
}
System.out.print(node.value + " "); /* first print data of node */
printPreorder(node.left); /* then recur on left subtree */
printPreorder(node.right); /* now recur on right subtree */
}
void printPreorder() {
printPreorder(root);
}
这就是我陷入困境的地方:如何打印特定节点之后的节点,而不仅仅是整个树?我以为会是:
public TreeNode findPreorder(int key) // find node with given key
{ // (assumes non-empty tree)
TreeNode current = root; // start at root
while (current.value == key) // while there is a match
{
current = current.left;
if (key < current.value) // go left?
{
current = current.right;
} else {
current = current.right; // or go right?
}
if (current == null) // if no child,
{
return null; // didn't find it
}
}
return current; // found it
}
但那不起作用。这是我主要的测试代码:
public static void main(String[] args) {
BTree2 tree = new BTree2();
tree.root = new TreeNode(1);
tree.root.left = new TreeNode(2);
tree.root.right = new TreeNode(3);
tree.root.left.left = new TreeNode(4);
tree.root.left.right = new TreeNode(5);
System.out.println("Preorder traversal of binary tree is ");
tree.printPreorder();
System.out.println("the node after 1 is " + tree.findPreorder(1).value);
}
我的输出是:
二叉树的前序遍历为1 2 4 5 3
1之后的节点是5
有任何想法吗?谢谢!!