2014-04-30 126 views
1

在下面的程序,树节点数据结构的解释

这是什么意思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

no,'node'不一定与'this'相同,它是正在设置的'left'的根。 –

回答

3

没有底部的代码是不正确的。在底部实现中,你所做的是将左侧子节点实际上作为类的父节点。如果您已经位于的节点不是根节点,则左侧子节点设置正确,但左侧子节点没有正确设置父节点。

下面的图像是在底部

enter image description here

下面的图像执行的代码的结果是执行顶块(这是正确的)

enter image description here

1

假设你没有

TreeNode a = new TreeNode (1); 

在这个时候的leftrightroot是空

,如果你没有

​​

那么现在一个是rightroot仍然无效,但leftb

和b的root现在是a

+0

所以哪个实现是正确的? 你能告诉我我的第一和第二种方法吗?怎么了?以及我是如何在其中的一个 – fscore

+0

错误的哪些实现是正确的取决于您的业务逻辑。你想实现什么?我会说,如果你将A的左边设置为B,那么B的右边应该是A-eh? –