建设银行龙卡信用卡官方网站,外包工是临时工吗,旅游景点网站策划书,app应用公司二叉树的定义就不在这里多说了#xff0c;下面这个图就是一个简单的二叉树#xff1a;
二叉树的三种遍历方式#xff1a;
前序遍历#xff1a;头左右#xff0c;也就是先头后左再右#xff1a;1245367 public static void prePrint(BinaryTreeNode root) {if (root ! n…二叉树的定义就不在这里多说了下面这个图就是一个简单的二叉树
二叉树的三种遍历方式
前序遍历头左右也就是先头后左再右1245367 public static void prePrint(BinaryTreeNode root) {if (root ! null) {System.err.print(root.val);prePrint(root.left);prePrint(root.right);}}
中序遍历左头右也就是先左后头再右4251637 public static void midPrint(BinaryTreeNode root) {if (root ! null) {midPrint(root.left);System.err.print(root.val);midPrint(root.right);}}
后序遍历左头右也就是先左后右再头4526731 public static void posPrint(BinaryTreeNode root) {if (root ! null) {posPrint(root.left);posPrint(root.right);System.err.print(root.val);}}
测试代码
class BinaryTreeNode {int val;BinaryTreeNode left;BinaryTreeNode right;public BinaryTreeNode(int val) {this.val val;}public BinaryTreeNode(int val, BinaryTreeNode left, BinaryTreeNode right) {this.val val;this.left left;this.right right;}
} public static void main(String[] args) {BinaryTreeNode one new BinaryTreeNode(1,new BinaryTreeNode(2, new BinaryTreeNode(4, null, null), new BinaryTreeNode(5, null, null)),new BinaryTreeNode(3, new BinaryTreeNode(6, null, null), new BinaryTreeNode(7, null, null)));prePrint(one);System.err.println();midPrint(one);System.err.println();posPrint(one);}
那么我们可以看出来不论是哪种遍历方式其在处理左右子节点的时候逻辑都是一样的都是要递归处理不同的只是头结点的输出时机那么可以优化成下面的代码 public static void print(BinaryTreeNode root, int type) {switch (type) {case 1:if (root ! null) {System.err.print(root.val);print(root.left, 1);print(root.right, 1);}break;case 2:if (root ! null) {print(root.left, 2);System.err.print(root.val);print(root.right, 2);}break;case 3:if (root ! null) {print(root.left, 3);print(root.right, 3);System.err.print(root.val);}break;}}