按层次遍历树结构

为君一笑 提交于 2020-01-22 01:12:01

解法1

package tree.leveltraversal;

import tree.Node;
import tree.myavl.BalanceTree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by lijie35 on 2020-01-21 10:45 AM .
 */
public class LevelTraversal2 {
    public static void main(String[] args) {
        BalanceTree bl=new BalanceTree();
        bl.put(10);
        bl.put(5);
        bl.put(15);
        bl.put(4);
        bl.put(7);
        bl.put(11);
        bl.put(16);
        Queue queue1 = new LinkedList();

        queue1.add(bl.root);
       LevelTraversal2.cycle(queue1);

        System.out.println(queue1);


    }

    public static void cycle(Queue<Node> queue ) {
        if (queue.size() == 0)
            return;

        while (queue.size() > 0) {
            Node poll = queue.poll();
            System.out.println(poll.val);

            if (poll.leftChild != null)
                queue.add(poll.leftChild);
            if (poll.rightChild != null)
                queue.add(poll.rightChild);
        }
        cycle(queue);


    }

}

package tree.leveltraversal;

import tree.Node;
import tree.myavl.BalanceTree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by lijie35 on 2020-01-21 10:45 AM .
 */
public class LevelTraversal1 {
    public static void main(String[] args) {
        BalanceTree bl=new BalanceTree();
        bl.put(10);
        bl.put(5);
        bl.put(15);
        bl.put(4);
        bl.put(7);
        bl.put(11);
        bl.put(16);
        Queue queue1 = new LinkedList();
        Queue queue2 = new LinkedList();
        queue1.add(bl.root);
       LevelTraversal1.cycle(queue1,queue2);

        System.out.println(queue2);


    }

    public static void cycle(Queue<Node> queue ,Queue<Node> all) {
        if (queue.size() == 0)
            return;
        Queue queue1 = new LinkedList();
        while (queue.size() > 0) {
            Node poll = queue.poll();
            System.out.println(poll.val);
            all.add(poll);
            if (poll.leftChild != null)
                queue1.add(poll.leftChild);
            if (poll.rightChild != null)
                queue1.add(poll.rightChild);
        }
        cycle(queue1,all);


    }

}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!