二叉树的三种遍历方式
本文重点在二叉树的遍历,不考虑别的问题
1 package com.bjpowernode.test.datastructure; 2 3 import javax.swing.tree.TreeNode; 4 import java.util.ArrayList; 5 import java.util.List; 6 7 /** 8 * 二叉树的三种遍历方式 9 * 前序,根、左、右 10 * 中序遍历:左、根、右 11 * 后序遍历:左、右、根 12 */ 13 public class MyBinaryTree { 14 15 private static List<Integer> result = new ArrayList<Integer>(); 16 17 public static void main(String[] args) { 18 MyBinaryTree myBinaryTree = new MyBinaryTree(); 19 /** 20 * 模拟创造一个二叉树 21 * 6 22 * 4 7 23 * 3 5 9 24 * 2 25 * 26 */ 27 28 MyTreeNode myTreeNode = new MyTreeNode(6); 29 30 myTreeNode.left = new MyTreeNode(4); 31 32 myTreeNode.right = new MyTreeNode(7); 33 34 myTreeNode.left.left = new MyTreeNode(3); 35 36 myTreeNode.left.left.left = new MyTreeNode(2); 37 38 myTreeNode.right.right = new MyTreeNode(9); 39 40 myTreeNode.left.right = new MyTreeNode(5); 41 42 myBinaryTree.preTraverse(myTreeNode); 43 System.out.print("前序遍历==>"); 44 for (int k : result) { 45 System.out.print(k); 46 } 47 result.clear(); 48 System.out.println(); 49 50 myBinaryTree.inorderTraverse(myTreeNode); 51 System.out.print("中序遍历==>"); 52 for (int k : result) { 53 System.out.print(k); 54 } 55 result.clear(); 56 System.out.println(); 57 58 myBinaryTree.followTraverse(myTreeNode); 59 System.out.print("后序遍历==>"); 60 for (int k : result) { 61 System.out.print(k); 62 } 63 result.clear(); 64 65 66 67 } 68 69 70 /** 71 * 前序遍历 72 * @param root 73 */ 74 public void preTraverse(MyTreeNode root) { 75 if (root != null) { 76 result.add(root.value); 77 if (root.left != null) { 78 preTraverse(root.left); 79 } 80 81 if (root.right != null) { 82 preTraverse(root.right); 83 } 84 } 85 } 86 87 /** 88 * 中序遍历 89 * @param root 90 */ 91 public void inorderTraverse(MyTreeNode root) { 92 if (root != null) { 93 if (root.left != null) { 94 inorderTraverse(root.left); 95 } 96 result.add(root.value); 97 if (root.right != null) { 98 inorderTraverse(root.right); 99 } 100 } 101 } 102 103 /** 104 * 后序遍历 105 * @param root 106 */ 107 public void followTraverse(MyTreeNode root) { 108 if (root != null) { 109 if (root.left != null) { 110 followTraverse(root.left); 111 } 112 if (root.right != null) { 113 followTraverse(root.right); 114 } 115 result.add(root.value); 116 } 117 } 118 static class MyTreeNode { 119 int value; 120 MyTreeNode left; 121 MyTreeNode right; 122 public MyTreeNode(int value) { 123 this.value = value; 124 } 125 } 126 }
输出结果: