首页 > 代码库 > 二叉树前中后递归遍历
二叉树前中后递归遍历
1 public class Node { 2 public int value; 3 public Node left; 4 public Node right; 5 6 public Node (int data){ 7 this.value =http://www.mamicode.com/ data; 8 } 9 }
1 public class BinaryTreeMethod { 2 3 /** 4 * 二叉树递归前序遍历 5 * @param head 6 */ 7 public void preOrderRecur(Node head){ 8 if(head == null){ 9 return; 10 } 11 System.out.print(head.value + " "); 12 preOrderRecur(head.left); 13 preOrderRecur(head.right); 14 } 15 16 /** 17 * 二叉树递归中序遍历 18 * @param head 19 */ 20 public void inOrderRecur(Node head){ 21 if(head == null){ 22 return; 23 } 24 inOrderRecur(head.left); 25 System.out.print(head.value + " "); 26 inOrderRecur(head.right); 27 } 28 29 /** 30 * 二叉树递归后序遍历 31 * @param head 32 */ 33 public void postOrderRecur(Node head){ 34 if(head == null){ 35 return; 36 } 37 postOrderRecur(head.left); 38 postOrderRecur(head.right); 39 System.out.print(head.value + " "); 40 } 41 }
测试代码:
1 public class Test { 2 3 public static void main(String[] args){ 4 Node head = new Node(3); 5 Node left = new Node(5); 6 Node right = new Node(2); 7 head.left = left; 8 head.right = right; 9 10 left.left = new Node(1); 11 right.left = new Node(7); 12 13 BinaryTreeMethod method = new BinaryTreeMethod(); 14 method.preOrderRecur(head); 15 System.out.println(); 16 method.inOrderRecur(head); 17 System.out.println(); 18 method.postOrderRecur(head); 19 } 20 }
二叉树前中后递归遍历
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。