我有一个Node
类class Node{
int val;
Node parent;
Node left;
Node right;
public Node (int val){
this.val = val;
}
}
我有几个方法:
public class Tree{
public Node root = null;
void insertNodeSorted(Node x, Node tree) {
if (x.val < tree.val) {
if (tree.left == null) {
tree.left = x;
}
else
insertNodeSorted(x, tree.left);
}
else {
if (tree.right == null) {
tree.right = x;
}
else
insertNodeSorted(x, tree.right);
}
} // end insertNodeSorted
void deleteNodeSorted(Node x) {
if (root == null)
return;
else
root = deleteNodeSorted(x, root);
}
Node deleteNodeSorted(Node x, Node tree) {
if (x.val < tree.val)
tree.left = deleteNodeSorted(x, tree.left);
else if (x.val > tree.val)
tree.right = deleteNodeSorted(x, tree.right);
else
tree = replaceNodeSorted(tree);
return tree;
} // end deleteNodeSorted
// Additional Method
Node replaceNodeSorted(Node tree) {
if (tree.right == null)
tree = tree.left;
else if (tree.left == null)
tree = tree.right;
else
tree.right = findReplacement(tree.right, tree);
return tree;
} // end replaceNodeSorted
Node findReplacement(Node tree, Node replace) {
if (tree.left != null)
tree.left = findReplacement(tree.left, replace);
else {
replace.val = tree.val;
tree = tree.right;
}
return tree;
} // end findReplacement
我想编译树,但我不知道我需要在main方法中编写什么。
public static void main(String[] args){
Tree t = new Tree();
t.insertNodeSorted();
为了打印树,我需要在括号中写什么? (我知道我仍然需要在方法中添加System.out.println(val);)
答案 0 :(得分:1)
您定义了一个包含root
节点的变量,因此没有必要为方法tree
传递参数insertNodeSorted
。您始终可以使用root
节点。
添加一个只带一个参数的方法。
public void insertNodeSorted(Node x) {
if (root == null) {
root = x;
return;
}
insertNodeSorted(x, root);
}
使用两个参数private
private void insertNodeSorted(Node x, Node tree) {
...
}
现在您可以按以下方式插入元素:
Tree t = new Tree();
t.insertNodeSorted(new Node(1));
t.insertNodeSorted(new Node(134));
t.insertNodeSorted(new Node(13));
t.insertNodeSorted(new Node(4));
...