递归深度优先:
1 package xh_algorithm.chapter03; 2 3 import java.util.Arrays; 4 import java.util.LinkedList; 5 6 /** 7 * @author zsh 8 * @site qqzsh.top 9 * @create 2019-08-15 10:28 10 * @description 二叉树的遍历 11 * 递归实现 12 */ 13 public class Main1 { 14 15 /** 16 * 创建二叉树 17 * @param inputList 输入序列 18 * @return 19 */ 20 public static TreeNode createBinaryTree(LinkedList<Integer> inputList){ 21 TreeNode node = null; 22 if (inputList == null || inputList.isEmpty()){ 23 return null; 24 } 25 Integer date = inputList.removeFirst(); 26 if (date != null){ 27 node = new TreeNode(date); 28 node.leftChild = createBinaryTree(inputList); 29 node.rightChild = createBinaryTree(inputList); 30 } 31 return node; 32 } 33 34 /** 35 * 二叉树的前序遍历 36 * @param node 二叉树节点 37 */ 38 static void preOrderTraveral(TreeNode node){ 39 if (node == null){ 40 return; 41 } 42 //根左右 43 System.out.println(node.data); 44 preOrderTraveral(node.leftChild); 45 preOrderTraveral(node.rightChild); 46 } 47 48 /** 49 * 二叉树的中序遍历 50 * @param node 二叉树节点 51 */ 52 static void inOrderTreveral(TreeNode node){ 53 if (node == null){ 54 return; 55 } 56 //左根右 57 inOrderTreveral(node.leftChild); 58 System.out.println(node.data); 59 inOrderTreveral(node.rightChild); 60 } 61 62 /** 63 * 二叉树的后序遍历 64 * @param node 二叉树节点 65 */ 66 static void postOrderTreveral(TreeNode node){ 67 if (node == null){ 68 return; 69 } 70 //左右根 71 postOrderTreveral(node.leftChild); 72 postOrderTreveral(node.rightChild); 73 System.out.println(node.data); 74 } 75 76 public static void main(String[] args) { 77 LinkedList<Integer> inputList = new LinkedList<>(Arrays.asList(new Integer[]{ 78 3,2,9,null,null,10,null,null,8,null,4 79 })); 80 TreeNode treeNode = createBinaryTree(inputList); 81 System.out.println("前序遍历"); 82 preOrderTraveral(treeNode); 83 System.out.println("中序遍历"); 84 inOrderTreveral(treeNode); 85 System.out.println("后序遍历"); 86 postOrderTreveral(treeNode); 87 } 88 } 89 90 /** 91 * 二叉树节点 92 */ 93 class TreeNode{ 94 int data; 95 TreeNode leftChild; 96 TreeNode rightChild; 97 98 public TreeNode(int data) { 99 this.data = data; 100 } 101 }