public class BinaryTree { public static TreeNode generateTree(int[] nums,int index){ TreeNode root=null; if (index<nums.length) { root=new TreeNode(nums[index]); root.LChild=generateTree(nums, 2*index+1); root.RChild=generateTree(nums, 2*index+2); } return root; }
public static void levelOrder(TreeNode root){ Queue<TreeNode> queue=new LinkedList<TreeNode>(); if (root == null) { return; } TreeNode node=root; queue.add(root); while (!queue.isEmpty()){ node=queue.peek(); System.out.print(node.val+" "); if (node.LChild != null) { queue.add(node.LChild); } if (node.RChild != null) { queue.add(node.RChild); } queue.poll(); } } public static void preOrder(TreeNode root){ if (root==null) return; System.out.print(root.val+" "); preOrder(root.LChild); preOrder(root.RChild); } public static void inOrder(TreeNode root){ if (root == null) return; inOrder(root.LChild); System.out.print(root.val+" "); inOrder(root.RChild); } public static void postOrder(TreeNode root){ if (root == null) return; postOrder(root.LChild); postOrder(root.RChild); System.out.print(root.val+" "); }}
class TreeNode{ int val; TreeNode LChild; TreeNode RChild;
public TreeNode(int val) { this.val = val; this.LChild = null; this.RChild = null; }}