在以下计划中,
这意味着什么left.parent = this;
我知道它让左孩子的父母成为' this
'但到底是什么this
。这指的是当前实例方法对吗?但任何人都可以解释得更好。
public class TreeNode {
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode root;
private int size = 0;
public TreeNode(int d) {
data = d;
size = 1;
}
public void setLeftChild(TreeNode left) {
this.left = left;
if (left != null) {
left.root= this;
}
}
上面的函数setLeftChild
是否会像下面的函数一样表示:
void setLeftChild(TreeNode node)
{
if(root == null)
{
this.root = node;
}
else
{
this.left = node;
}
}
答案 0 :(得分:3)
底部代码不正确。在底层实现中,您所做的是将左子节点实际上作为类的父节点。如果您所在的节点不是根节点,则左子节点设置正确,但左子节点未正确设置其父节点。
下图是执行底部
代码的结果
下面的图像是执行顶部块(正确)的结果
答案 1 :(得分:1)
假设你做了
TreeNode a = new TreeNode (1);
目前,left
,right
和root
为空
如果你做了
TreeNode b = new TreeNode (b);
a.setLeftChild (b);
然后现在right
和root
仍为空,left
为b
和b root
现在是a
答案 2 :(得分:-2)