递归遍历 (前序、中序、后序遍历)
/**
* 前序遍历
*/
public static void preOrder(TreeNode node) {
if (Objects.isNull(node)) {
return;
}
System.out.print(node.data + " ");
preOrder(node.leftChild);
preOrder(node.rightChild);
}
/**
* 中序遍历
*/
public static void inOrder(TreeNode node) {
if (Objects.isNull(node)) {
return;
}
inOrder(node.leftChild);
System.out.print(node.data + " ");
inOrder(node.rightChild);
}
/**
* 后序遍历
*/
public static void postOrder(TreeNode node) {
if (Objects.isNull(node)) {
return;
}
postOrder(node.leftChild);
postOrder(node.rightChild);
System.out.print(node.data + " ");
}
/**
* 测试案例
*/
public static void main(String[] args) {
LinkedList<Integer> datas = new LinkedList<>(Arrays.asList(3,2,9,null,null,10,null,null,8,null,4));
TreeNode treeNode = TreeNode.createTreeNode(datas);
System.out.println("前序遍历");
preOrder(treeNode);
System.out.println();
System.out.println("中序遍历");
inOrder(treeNode);
System.out.println();
System.out.println("后序遍历");
postOrder(treeNode);
}
打印结果
前序遍历
3 2 9 10 8 4
中序遍历
9 2 10 3 8 4
后序遍历
9 10 2 4 8 3
非递归遍历 (层序遍历)
/**
* 层序遍历
*/
public static void stackOrder(TreeNode treeNode) {
Queue<TreeNode> queue = new LinkedList<>();
queue.add(treeNode);
while (!queue.isEmpty()) {
TreeNode poll = queue.poll();
System.out.print(poll.data + " ");
if (poll.leftChild != null) {
queue.add(poll.leftChild);
}
if (poll.rightChild != null) {
queue.add(poll.rightChild);
}
}
}
public static void main(String[] args){
LinkedList<Integer> datas = new LinkedList<>(Arrays.asList(1,2,4,null,null,5,null,null,3,null,6));
TreeNode treeNode = TreeNode.createTreeNode(datas);
System.out.println("层序遍历: ");
stackOrder(treeNode);
}
打印结果
层序遍历:
1 2 3 4 5 6