java多叉树层次遍历

java多叉树的层次遍历,个人树好像不太同样大笑,看代码吧。代码中的LLQueue 就是一个单链表实现的队列。java

思路与二叉树的层次遍历同样。遍历一层的时候,把下层的节点放到队列中。就是操做有点不一样。dom

/**
 * 功能 :
 * date : 2018/5/28
 *
 * @author : zcwang@wisdombud.com
 * @version : 0.0.4-snapshot
 * @since : JDK 1.8
 */
public class TreeNode<T> {
    T data;
    private TreeNode<T> firstChild;
    private TreeNode<T> nextSibling;

    public TreeNode(final T data, final TreeNode<T> firstChild, final TreeNode<T> nextSibling) {
        this.data = data;
        this.firstChild = firstChild;
        this.nextSibling = nextSibling;
    }

    public TreeNode(final T data) {
        this(data, null, null);
    }

    public static void main(String args[]) {
        TreeNode<Integer> treeNode = new TreeNode<>(1);
        TreeNode<Integer> firstChild = new TreeNode<>(2);
        TreeNode<Integer> nextSibling = new TreeNode<>(3);
        TreeNode<Integer> nextSibling1 = new TreeNode<>(4);
        TreeNode<Integer> nextSibling2 = new TreeNode<>(5);

        TreeNode<Integer> firstChild1 = new TreeNode<>(6);
        TreeNode<Integer> nextSibling11 = new TreeNode<>(7);
        TreeNode<Integer> nextSibling12 = new TreeNode<>(8);

        TreeNode<Integer> firstChild2 = new TreeNode<>(9);
        TreeNode<Integer> nextSibling21 = new TreeNode<>(10);
        TreeNode<Integer> nextSibling22 = new TreeNode<>(11);
        treeNode.setFirstChild(firstChild);
        firstChild.setNextSibling(nextSibling);
        nextSibling.setNextSibling(nextSibling1);
        nextSibling1.setNextSibling(nextSibling2);

        nextSibling.setFirstChild(firstChild1);
        firstChild1.setNextSibling(nextSibling11);
        nextSibling11.setNextSibling(nextSibling12);

        nextSibling1.setFirstChild(firstChild2);
        firstChild2.setNextSibling(nextSibling21);
        nextSibling21.setNextSibling(nextSibling22);
        levelOrder(treeNode);
    }

    public static void levelOrder(TreeNode<Integer> root) {
        if (root == null) {
            return;
        }
        TreeNode<Integer> temp;
        LLQueue<TreeNode> queue = new LLQueue<>();
        queue.enQueue(root);
        while (!queue.isEmpty()) {
            temp = queue.deQueue();
            System.out.println(temp.getData());
            //判断是否存在孩子节点
            if (temp.getFirstChild() != null) {
                queue.enQueue(temp.getFirstChild());
                temp = temp.getFirstChild();
                // 若是存在兄弟 就一直向queue中放
                while (temp.getNextSibling() != null) {
                    queue.enQueue(temp.getNextSibling());
                    temp = temp.getNextSibling();
                }
            }
        }
    }
}