如何打印第一个孩子 - 兄弟姐妹结构

时间:2015-10-06 13:39:46

标签: java recursion binary-tree nodes siblings

我正在试图找出如何打印第一个孩子的下一个兄弟树。我想要的是以下内容:

root
|
firstChild - sibling - sibling
                       |
                       child - sibling - sibling 

我有以下代码来添加孩子和兄弟姐妹:

class Program
{
    static void Main(string[] args)
    {
        GeneralTree<string> tree = new GeneralTree<string>();
        tree.root = new TreeNode<string>
        {
            Data = "Root"
        };
        TreeNode<string> child = tree.addChild(tree.root, "Child");
        tree.addSibling(child, "Sibling");
        tree.print(tree.root);
    }
}
class GeneralTree<T>
{
    public TreeNode<T> root;

    public TreeNode<T> addChild(TreeNode<T> parent, T data)
    {
        parent.FirstChild = new TreeNode<T>
        {
            Data = data,
            NextSibling = parent.FirstChild
        };
        return parent.FirstChild;
    }
    public TreeNode<T> addSibling(TreeNode<T> sibling, T data)
    {
        sibling.NextSibling = new TreeNode<T>
        {
            Data = data,
            FirstChild = sibling.NextSibling
        };
        return sibling.NextSibling;
    }

    int count = 0;
    public void print(TreeNode<T> Node)
    {

        if(Node !=null)
        {
            Console.WriteLine(Node.Data);
            print(Node.FirstChild);
            ++count;
            Console.WriteLine(count);
            print(Node.NextSibling);
        }
    }
}
class TreeNode<T>
{
    public T Data { get; set; }
    public TreeNode<T> FirstChild { get; set; }
    public TreeNode<T> NextSibling { get; set; }
}

现在有人怎么打印出来?

提前致谢!

1 个答案:

答案 0 :(得分:0)

我选择以这种方式合并TreeNodeGeneralTree

public class TreeNode<T> 
{

    public T data;
    public List<TreeNode<T>> childs;

    public TreeNode<T> firstChild()
    {return childs.get(0);}

    public void appendChild(TreeNode<T> child)
    {childs.add(child);}

    public void print() {/* ... */}

    /* ... */

    public static void main(String args[])
    { /* ... */}
}

然后,一种递归写print()的方法:

    public void print()
    {
        print(0);    
    }

    public void print(int offset)
    {
        if (node == null) return; // nothing to print anymore

        System.out.println(this.data); // printing the root data

        TreeNode<T> lastChild=null;
        String output = "";
        for(Iterator<TreeNode<T>> i = childs.iterator(); i.hasNext(); )
        {   
            lastChild = i.next();
            if (output != "") output += " - ";
            output += lastChild.data;
        }

        // length will be the next line offset
        // (size of the current line output minus last item length

        int length = output.length()-lastChild.toString().length;
        // use a repeat() string function like this one :
        output = org.apache.commons.lang.StringUtils.repeat(" ", length) + (length>0?"|":"") + output;
        System.out.println (output);
        lastChild.print(length);
    }

}

很遗憾,我现在无法验证我的代码,如果您遇到问题,请告知我们。