标签:str private deque row 二叉树 访问 ace trace round
/* * 二叉树的层次遍历 * 1.首先将根节点放入队列中。 2.当队列为非空时,循环执行步骤3到步骤5,否则执行6; 3.出队列取得一个结点,访问该结点; 4.若该结点的左子树为非空,则将该结点的左子树入队列; 5.若该结点的右子树为非空,则将该结点的右子树入队列; 6.结束。 */
import java.util.Queue;
public class BinaryTree<T> { private T data; private BinaryTree<T> left; private BinaryTree<T> right; private BinaryTree(T data) { this.data = data; } public BinaryTree() { } //层次遍历 public static void levelTraverse(BinaryTree root) { if(root==null) { try { throw new Exception("二叉树为空"); }catch (Exception e) { e.printStackTrace(); } }else { Queue<BinaryTree> queue = new Queue<BinaryTree>(); queue.enqueue(root); while(!queue.isEmpty()) { root = queue.dequeue(); System.out.print(root.data + " "); if(root.left != null) queue.enqueue(root.left); if(root.right != null) queue.enqueue(root.right); } } } //换行层次遍历 public static void newLevelTraverse(BinaryTree root) { BinaryTree last = new BinaryTree(); BinaryTree nlast = new BinaryTree(); if(root==null) { try { throw new Exception("二叉树为空"); }catch (Exception e) { e.printStackTrace(); } }else { Queue<BinaryTree> queue = new Queue<BinaryTree>(); queue.enqueue(root); last = root;//last表示正在打印的当前行 的最右节点 nlast = root;//nlast表示下一行的最右节点,nlast节点每次跟踪记录最先加入队列的节点 while(!queue.isEmpty()) { root = queue.dequeue(); System.out.print(root.data+" "); if(root.left != null) { queue.enqueue(root.left); nlast = root.left; } if(root.right != null) { queue.enqueue(root.right); nlast = root.right; } //如果当前输出节点root是最右节点last,那么换行 if(last == root) { System.out.println(); last = nlast;//last节点更新为nlast节点 } } } } public static void main(String[] args) { BinaryTree b1 = new BinaryTree(1); BinaryTree b2 = new BinaryTree(2); BinaryTree b3 = new BinaryTree(3); BinaryTree b4 = new BinaryTree(4); BinaryTree b5 = new BinaryTree(5); BinaryTree b6 = new BinaryTree(6); BinaryTree b7 = new BinaryTree(7); BinaryTree b8 = new BinaryTree(8); b1.left = b2; b1.right = b3; b2.left = b4; b3.left = b5; b3.right = b6; b5.left = b7; b5.right = b8; //层次遍历二叉树 BinaryTree.levelTraverse(b1);
//换行层次遍历
BinaryTree.newLevelTraverse(b1); } }
标签:str private deque row 二叉树 访问 ace trace round
原文地址:http://www.cnblogs.com/huyingjie/p/7748433.html