首页 > 代码库 > JAVA按层级遍历二叉树

JAVA按层级遍历二叉树

/**
 * @author cj 2017年7月14日下午1:14:31
 */
package com.yuanye.algorithm;

import java.util.LinkedList;
import java.util.List;

public class BinaryTree {
//    private static List<Node> currentLevelNodes=new ArrayList<>();
//    private static List<Node> nextLevelNodes=new ArrayList<>();
    private static List<Node> nodeList=new LinkedList<>();
    
    public static void main(String[] args) {
        Node rootNode=new Node();
        rootNode.setValue(88);
        generateTree(rootNode,5,0);
        printTree(rootNode);
    }
    public static void generateTree(Node parentNode,int depth,int currentDepth){
        if(currentDepth>depth-1)
            return;
        Node leftNode=new Node();
        leftNode.setValue(6000+currentDepth);
        Node rightNode=new Node();
        rightNode.setValue(9000+currentDepth);
        parentNode.setLeftNode(leftNode);
        parentNode.setRightNode(rightNode);
        generateTree(leftNode,depth,currentDepth+1);
        generateTree(rightNode,depth,currentDepth+1);
    }
    public static void printTree(Node rootNode){
        System.out.println(rootNode.getValue());
        Node leftNode=rootNode.getLeftNode();
        Node rightNode=rootNode.getRightNode();
        if(leftNode!=null){
            nodeList.add(leftNode);
        }
        if(rightNode!=null){
            nodeList.add(rightNode);
        }
//        if(currentLevelNodes.size()==0){
//            currentLevelNodes.addAll(nextLevelNodes);
//            nextLevelNodes.removeAll(nextLevelNodes);
//        }
//        if(currentLevelNodes.size()>0){
//            Node nextNode=currentLevelNodes.get(0);
//            currentLevelNodes.remove(0);
//            printTree(nextNode);
//        }
        if(nodeList.size()>0){
            Node nextNode=nodeList.get(0);
            nodeList.remove(0);
            printTree(nextNode);
        }
    }
}
class Node{
    private int value;
    private Node leftNode;
    private Node rightNode;
    
    public int getValue() {
        return value;
    }
    public void setValue(int value) {
        this.value =http://www.mamicode.com/ value;
    }
    public Node getLeftNode() {
        return leftNode;
    }
    public void setLeftNode(Node leftNode) {
        this.leftNode = leftNode;
    }
    public Node getRightNode() {
        return rightNode;
    }
    public void setRightNode(Node rightNode) {
        this.rightNode = rightNode;
    }
    @Override
    public String toString() {
        return "Node [value="http://www.mamicode.com/+ value +", leftNode=" + leftNode + ", rightNode=" + rightNode + "]";
    }
}

 

JAVA按层级遍历二叉树