我想反映一个二叉树,使左边的所有节点都结束在右边,反之亦然。两种递归方法之间的区别
喜欢的东西:
A
/ \
B C
/ / \
D E F
将成为
A
/ \
C B
/\ \
F E D
我注意到,在写我的解决方案,这个代码工作:
static Tree getReflection(Tree root) {
if(root == null) {
return null;
}
Tree reflect = root;
Tree subRight = getReflection(root.right);
Tree subLeft = getReflection(root.left);
reflect.left = subRight;
reflect.right = subLeft;
return reflect;
}
然而,这一次没有按” t:
static Tree getReflection(Tree root) {
if(root == null) {
return null;
}
Tree reflect = root;
reflect.left = getReflection(root.right);
reflect.right = getReflection(root.left);
return reflect;
}
有人可以向我解释为什么?对我来说,除了使用临时树变量外,它们看起来像是相同的方法。
所以我应该做一些像Tree reflect = new Tree(root.value)的东西。那么它会创建一个新对象而不是指向原始根的指针?这个想法是否正确? – Fiass
没错。你必须以某种方式得到新的副本,并且你的建议可以做到。 – Prune