我必须做一些关于BinaryTree的方法(没有搜索二叉树)。我无法做3种方法:反映(反映树,我的代码不起作用,因为只反映了树的一部分),cut和cut2。代码是:
public class BinaryTree {
protected class Node {
Integer element;
Node left;
Node right;
Node(int element) {
this.element = element;
left = right = null;
}
Node(int element, Node left, Node right) {
this.element = element;
this.left = left;
this.right = right;
}
// is leaf?
boolean isLeaf() {
return left == null && right == null;
}
}
protected Node root;
public BinaryTree() {
root = null;
}
/* doesn't work */
public void reflect() {
if (root == null)
return;
reflect(root);
}
protected void reflect(Node node) {
reflect(node.left);
reflect(node.right);
Node temp = new Node(node.left.element);
node.left.element = node.right.element;
node.right.element = temp.element;
}
/* this method had to trim the tree at level h,
if h=0, it cut the whole tree. It change the original tree */
/* doesn't work */
public void cut(int h) {
}
/* i can change parameters */
protected void cut(Node node, int h) {
}
/* this method had to trim the tree at level h,
if h=0, it cut the whole tree. It doesn't change the original tree,
it returns a new tree */
/* doesn't work */
public BinaryTree cut2(int h) {
}
/* i can change parameters */
protected BinaryTree cut2(Node node, int h) {
}
}
}
我无法做反射cut和cut2的方法。请帮帮我,谢谢!
答案 0 :(得分:0)
你差不多reflect
了。只是避免创建新的Node对象:
protected void reflect(Node node) {
if (node != null) {
reflect(node.left);
reflect(node.right);
Node temp = node.left;
node.left = node.right;
node.right = temp;
}
}
至于cut
:
public void cut(int h) {
if (h == 0) {
root = null;
} else {
cut(root, h - 1);
}
}
然后你可以写cut(Node, int)
:
protected void cut(Node node, int h) {
if (node != null) {
if (h == 0) {
node.left = node.right = null;
} else {
cut(node.left, h - 1);
cut(node.right, h - 1);
}
}
}
看看你是否可以自己使用上面的cut2
作为开始。
答案 1 :(得分:0)
这有点像家庭作业,即使标签被修剪,我也不认为我们编写完整的二叉树实现是正确的。
话虽如此,你能解释一下实施这两种方法还不清楚吗?除了cut2
所需的树复制外,它们几乎相同。我将通过递归私有方法cutInternal(Node n, int currLevel, int h)
实现它,传递我们当前所在的级别编号。然后,当currLevel == h
我们只修剪两个节点并返回时。