通过递归实现二叉树的三种遍历方法
用LinkedList链表的先序遍历来创建二叉树
二叉树的先序,中序,后序很容易就会弄蒙遍历者。
不妨这样记忆:先序,中序,后序其实说的是根节点的遍历顺序,
先序即根节点先遍历,先输出,遵循DFS(深度遍历法则)
中序即根节点晚于左子节点遍历,先于右子节点遍历,同样要遵循DFS(深度遍历法则)
后序即根节点最后遍历,遵循DFS(深度遍历法则)
一切都以深度遍历DFS为准 + 根节点的顺序就可以很好地实现二叉树的人为遍历。
首先是二叉树的节点构造如下:
package com.tree;
public class TreeNode<T> {
public T data;
public TreeNode<T> left;
public TreeNode<T> right;
public TreeNode(T data,TreeNode<T> left,TreeNode<T> right){
this.data = data;
this.left = left;
this.right = right;
}
}
二叉树的创建和遍历算法
此处创建二叉树有一个灵魂方法是LInkedList的RemoveFirst()方法即移除链表中的首个元素并返回这个首元素。这有利于我们始终得到树的根节点。
package com.tree;
import java.util.LinkedList;
/**
* @author:Dylan
* @detail 二叉树 各种遍历 先序创建
* @param <T>
*/
public class BinaryTree<T> {
/**
* 先序创建二叉树
* 返回:根节点
* @param treeData
*/
public TreeNode<T> creatBinaryPre(LinkedList<T> treeData){
TreeNode<T> root = null;
T data = treeData.removeFirst();
if (data != null){
root = new TreeNode<T>(data,null,null);
root.left = creatBinaryPre(treeData);
root.right = creatBinaryPre(treeData);
}
return root;
}
/**
* 先序遍历二叉树(递归)
*/
public void printBinaryTreePreRecur(TreeNode<T> root){
if (root != null){
System.out.println(root.data);
printBinaryTreePreRecur(root.left);
printBinaryTreePreRecur(root.right);
}
}
/**
* 中序遍历二叉树(递归)
*/
public void printBinaryTreeMidRecur(TreeNode<T> root){
if (root != null){
printBinaryTreePreRecur(root.left);
System.out.println(root.data);
printBinaryTreeMidRecur(root.right);
}
}
/**
*后序遍历二叉树(递归)
*/
public void printBinaryTreeBacRecur(TreeNode<T> root){
if (root != null){
printBinaryTreeBacRecur(root.left);
printBinaryTreeBacRecur(root.right);
System.out.println(root.data);
}
}
}
先序遍历创建二叉树,空节点用null值代替
package com.tree;
/**
* @author:Dylan
* 用先序遍历构建二叉树
* A
* B C
* D E F G
* H I J
*/
import java.util.LinkedList;
public class TreeTest {
public static void main(String[] args){
BinaryTree<Character> binaryTree = new BinaryTree<>();
LinkedList<Character> tree = new LinkedList<>();
tree.add('A');tree.add('B');tree.add('D');
tree.add('H');tree.add(null);tree.add(null);
tree.add('I');tree.add(null);tree.add(null);
tree.add('E');tree.add(null);tree.add(null);
tree.add('C');tree.add('F');tree.add(null);
tree.add('J');tree.add(null);tree.add(null);
tree.add('G');tree.add(null);tree.add(null);
TreeNode<Character> root = binaryTree.creatBinaryPre(tree);
//先序遍历(递归)
binaryTree.printBinaryTreePreRecur(root);
System.out.println();
//中序遍历(递归)
binaryTree.printBinaryTreeMidRecur(root);
System.out.println();
//后序遍历(递归)
binaryTree.printBinaryTreeBacRecur(root);
System.out.println();
}
}