在运行时组装二进制树节点

时间:2014-04-10 08:30:41

标签: c#

getTree方法必须回答一个Node对象,该对象的TAL = 2,而LEFT指向一个节点,其TAL = 1,RIGHT指向一个节点,其TAL = 3

任何人都可以在这里帮助我,我已经尝试了很多方法来使它像上面的描述......

 public class Test
{
    public Node getTree()
    {
        Node right = new Node();
        Node left = new Node();

        Node ny = new Node();
        ny.TAL = 2;

       Node ny2 = new Node();
       ny2.TAL = 1;

       Node ny3 = new Node();
       ny3.TAL = 3;

       left.LEFT = ny2;
       right.RIGHT = ny3;

    }
    public class Node
    {
        public int TAL;
        public Node LEFT;
        public Node RIGHT;

    }

}

2 个答案:

答案 0 :(得分:1)

 public class Test
{
    public Node getTree()
    {
        Node output = new Node();   // create tree root
        // create child nodes
        output.LEFT = new Node();
        output.RIGHT = new Node(); 
        //set TAL values
        output.TAL = 2;
        output.LEFT.TAL = 1;
        output.RIGHT.TAL = 3;
        //return tree
        return output;
    }
    public class Node
    {
        public int TAL;
        public Node LEFT;
        public Node RIGHT;

    }

}

您还可以使用构造函数来设置TAL属性:

 public class Test
{
    public Node getTree()
    {
        //creates root node with TAL=2 using Node(int) constructor
        Node output = new Node(2);
        //creates left and right child nodes
        output.LEFT = new Node(1);
        output.RIGHT = new Node(3);
        return output;
    }
    public class Node
    {
        public int TAL;
        public Node LEFT;
        public Node RIGHT;

        //Node constructor that set TAL field
        public Node(int tal)    
        {
              TAL = tal;
        }
    }

}

答案 1 :(得分:0)

当您只需要三个时,您正在创建五个Node对象。 试试这个:

public class Test
{
    public Node getTree()
    {
        // Create the nodes
        Node parent = new Node();
        Node right = new Node();
        Node left = new Node();

        // Link them
        parent.LEFT = left;
        parent.RIGHT = right;

        // Populate their values
        parent.TAL = 2;
        right.TAL = 3;
        left.TAL = 1;

        // Return the tree
        return parent;
    }

    public class Node
    {
        public int TAL;
        public Node LEFT;
        public Node RIGHT;
    }
}