JAVA按层级遍历二叉树
Posted 元页
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 = 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=" + value + ", leftNode=" + leftNode + ", rightNode=" + rightNode + "]"; } }
以上是关于JAVA按层级遍历二叉树的主要内容,如果未能解决你的问题,请参考以下文章
[每日算法0519] 二叉树逐层遍历和通过中序前序获取完整的树