二叉树前中后递归遍历
Posted huangyichun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树前中后递归遍历相关的知识,希望对你有一定的参考价值。
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 = 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 }
以上是关于二叉树前中后递归遍历的主要内容,如果未能解决你的问题,请参考以下文章