Java examples for Data Structure:Tree
Algorithm for binary Tree Level Travel
import java.util.*; public class Algorithm_binaryTreeLevelTravel{ public static void main(String[] args){ //from www .j av a2 s. c o m TreeNode root = new TreeNode(0); } public static void recurisionTravel(TreeNode root,int level){ if(root==null) return; else if(level==0) System.out.println(root.val); else{ recurisionTravel(root.left,level-1); recurisionTravel(root.right,level-1); } } public void iteratorTravel(TreeNode root){ Queue<TreeNode> queue = new LinkedList<TreeNode>();// an empty LinkedList. queue.offer(root); TreeNode node = new TreeNode(); queue.offer(node); // poll()&offer() will return null or false, if the queue is empty or is full(for a capability-restricted) while(queue.peek()!=null) { TreeNode node = queue.poll(); System.out.println(node.val()); queue.offer(node.left); queue.offer(node.right); } } } class TreeNode{ int val; TreeNode left; TreeNode right; public void TreeNode(int val){ this.val = val; } }