N叉树的java实现

一.什么是N叉树?
就是节点的孩子没有限制的树。

例如:
在这里插入图片描述

那么怎么表示这种树呢?

有一种方法可以合理的表示它:
1.同一个父母节点的孩子从左到右排列。
2.父母节点只指向第一个孩子节点。

如图:
在这里插入图片描述

它的节点定义和二叉树一样:

class BinaryTreeNode{
    private int data;
    private BinaryTreeNode first;
    private BinaryTreeNode next;
    BinaryTreeNode(int data)
    {
        this.data=data;
    }
    public int getData()
    {
        return data;
    }
    public void setData(int data)
    {
        this.data=data;
    }
    public void setLeft(BinaryTreeNode first)
    {
        this.first=first;
    }
    public BinaryTreeNode getFirst()
    {
        return first;
    }
    public void setRight(BinaryTreeNode next)
    {
        this.next=next;
    }
    public BinaryTreeNode getNext()
    {
        return next;
    }
}

这样就可以用二叉树来表示N叉树了。
故其遍历方法和上一篇博客的二叉树一样。

发布了73 篇原创文章 · 获赞 1 · 访问量 2450

猜你喜欢

转载自blog.csdn.net/c1776167012/article/details/105047805