题目:
使用递归完成二叉树的前序,中序遍历,后续遍历
代码实现:
package com.isea.brush.tree;
public class BinaryTree {
private Node head;
private int size;
private static class Node {
private int data;
private Node left;
private Node right;
public Node(int data) {
this.data = data;
}
}
public BinaryTree() {
head = null;
size = 0;
}
/**
* 二叉树的先序遍历
*
* @param head 二叉树的根节点
*/
public void preOrderRec(Node head) {
if (head == null) {
return;
}
System.out.println(head.data + " ");
preOrderRec(head.left);
preOrderRec(head.right);
}
/**
* 二叉树的中序遍历
*
* @param head 二叉树的根节点
*/
public void inOrderRec(Node head) {
if (head == null) {
return;
}
inOrderRec(head.left);
System.out.println(head.data + " ");
inOrderRec(head.right);
}
/**
* 二叉树的后序遍历
*
* @param head 二叉树的根节点
*/
public void postOrderRec(Node head) {
if (head == null) {
return;
}
postOrderRec(head.left);
postOrderRec(head.right);
System.out.println(head.data + " ");
}
}