Treenode数据结构说明

时间:2014-04-30 02:27:42

标签: java algorithm data-structures tree binary-tree

在以下计划中,

这意味着什么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;
        }
    }
  • 实施是否正确?第一和第二?
    • 如果没有,那么第二次实施有什么问题?反之亦然
  • 第一次和第二次实施有什么区别?

3 个答案:

答案 0 :(得分:3)

底部代码不正确。在底层实现中,您所做的是将左子节点实际上作为类的父节点。如果您所在的节点不是根节点,则左子节点设置正确,但左子节点未正确设置其父节点。

下图是执行底部

代码的结果

enter image description here

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

enter image description here

答案 1 :(得分:1)

假设你做了

 TreeNode a = new TreeNode (1);

目前,leftrightroot为空

如果你做了

TreeNode b = new TreeNode (b);
a.setLeftChild (b);

然后现在rightroot仍为空,leftb

和b root现在是a

答案 2 :(得分:-2)