版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wlittlefive/article/details/80490167
java多叉树的层次遍历,我的树好像不太一样,看代码吧。代码中的LLQueue 就是一个单链表实现的队列。
思路与二叉树的层次遍历一样。遍历一层的时候,把下层的节点放到队列中。就是操作有点不同。
/**
* 功能 :
* date : 2018/5/28
*
* @author : [email protected]
* @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();
}
}
}
}
}