文章目录
- 题目
- 思路
- 代码
- 运行结果
题目
二叉树及三种顺序的递归遍历
思路
代码
/**
* @Author: ggdpzhk
* @CreateTime: 2024-08-04
*
* 二叉树及三种顺序的递归遍历
* LeetCode 144. 二叉树的前序遍历
* LeetCode 94. 二叉树的中序遍历
* LeetCode 145. 二叉树的后序遍历
* LeetCode 102. 二叉树的层序遍历
*/
public class _017_Tree {
public static void main(String[] args) {
TreeNode head = new TreeNode(1);
head.left = new TreeNode(2);
head.right = new TreeNode(3);
head.left.left = new TreeNode(4);
head.left.right = new TreeNode(5);
head.right.left = new TreeNode(6);
head.right.right = new TreeNode(7);
System.out.println("先序遍历递归版");
preOrder(head);
System.out.println();
System.out.println("中序遍历递归版");
inOrder(head);
System.out.println();
System.out.println("后序遍历递归版");
postOrder(head);
System.out.println();
}
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
//先序打印所有节点 递归版
public static void preOrder(TreeNode head) {
if (head == null) {
return;
}
System.out.print(head.val + " ");//先遍历我自己
preOrder(head.left);//再遍历左子树
preOrder(head.right);//再遍历右子树
}
//中序打印所有节点,递归版
public static void inOrder(TreeNode head) {
if (head == null) {
return;
}
inOrder(head.left);
System.out.print(head.val+" ");//左树结束,回到我,打印我
inOrder(head.right);
}
//后序打印所有节点,递归版
public static void postOrder(TreeNode head) {
if(head == null){
return;
}
postOrder(head.left);
postOrder(head.right);
System.out.print(head.val+" ");//左树右树遍历结束,回到我,打印我
}
}