* 二叉树,先序遍历,中序遍历,后序遍历,层序遍历
* 先序遍历:先根,在左,在右
* 中序遍历:先左,在根,在右
* 后序遍历:先左,在右,在根
* 层序遍历:一层层的遍历
public class 二叉树几种遍历方式 {
public static List<Integer> preList = new ArrayList<>();
public static List<Integer> inList = new ArrayList<>();
public static List<Integer> afterList = new ArrayList<>();
/**
* 先序遍历
*/
public static void preRound(TreeNode root) {
if(root != null) {
preList.add(root.val);
preRound(root.left);
preRound(root.right);
}
}
/**
* 中序遍历
*/
public static void inRound(TreeNode root) {
if(root != null) {
inRound(root.left);
inList.add(root.val);
inRound(root.right);
}
}
/**
* 后序遍历
*/
public static void afterRound(TreeNode root) {
if(root != null) {
afterRound(root.left);
afterRound(root.right);
afterList.add(root.val);
}
}
/**
* 层序遍历
*/
public static List<List<Integer>> layerRound(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if(root == null) {
return result;
}
Queue<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
// 总节点数
int sumNodeCount = 0;
// 叶子节点总数
int leftNodeCount = 0;
// 树的深度
int treeDepth = 0;
while (!queue.isEmpty()) {
// while循环几次代表树有多少层
treeDepth++;
List<Integer> layerList = new ArrayList<>();
int size = queue.size();
// sumNodeCount += size;
// 这是每一层有有多少个节点数
for (int i = 0; i < size; i++) {
TreeNode poll = queue.poll();
// 记录节点总数
sumNodeCount++;
layerList.add(poll.val);
if(poll.left != null) {
queue.offer(poll.left);
}
if(poll.right != null) {
queue.offer(poll.right);
}
if(poll.left == null && poll.right == null) {
leftNodeCount++;
}
}
result.add(layerList);
}
return result;
}
/**
* 计算树的深度,这种递归思想需要理解
*/
public static int depthTree(TreeNode root) {
if(root == null) {
return 0;
}
int leftDepth = depthTree(root.left);
int rightDepth = depthTree(root.right);
return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
}
// 树的总节点数,在层次遍历中可以统计----->树的深度,树的总节点数,树的叶子节点总数,
private static int count = 0;
/**
* 计算树节点的总数
*/
public static void nodeCount(TreeNode root) {
if(root == null) {
return;
}
count++;
nodeCount(root.left);
nodeCount(root.right);
}
private static int leftCount = 0;
/**
* 计算该树的叶子节点总数
*/
public static void leftNodeCount(TreeNode root) {
if(root == null) {
return;
}
if(root.left == null && root.right == null) {
leftCount++;
}
leftNodeCount(root.left);
leftNodeCount(root.right);
}
public static void main(String[] args) {
}
}
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}