1.二叉树前中后序遍历(递归)
核心思想:递归处理
- 前序:根左右
- 中序:左根右
- 后序:左右根
class Node {
public char val;
public Node left;
public Node right;
public Node(char val) {
this.val = val;
}
}
public class TestTree {
// 先序
public static void preOrder(Node root) {
if (root == null) {
return;
}
System.out.print(root.val + " ");
preOrder(root.left);
preOrder(root.right);
}
// 中序
public static void inOrder(Node root) {
if (root == null) {
return;
}
inOrder(root.left);
System.out.print(root.val + " ");
inOrder(root.right);
}
// 后序
public static void postOrder(Node root) {
if (root == null) {
return;
}
postOrder(root.left);
postOrder(root.right);
System.out.print(root.val + " ");
}
}
2.二叉树层次遍历
链接:层次遍历及相关问题
3.计算所有节点个数
核心思想:整个树节点个数 = 根结点的个数(1) + 左子树节点个数(递归) + 右子树节点个数(递归)
。
// 计算节点个数
public static int size(Node root){
if(root == null){
return 0;
}
// 递归思想 “拆分问题”
// 整个树节点个数 = 根结点的个数(1) + 左子树节点个数(递归) + 右子树节点个数(递归)
return 1 + size(root.left) + size(root.right);
}
4.计算叶子节点个数
核心思想:递归处理 叶子节点个数 = 左子树叶子节点个数 + 右子树叶子节点个数
。
// 计算叶子节点个数
public static int leafSise(Node root){
if(root == null){
return 0;
}
if(root.left==null && root.right==null){
return 1; // 叶子节点
}
// 叶子节点个数 = 左子树叶子节点个数 + 右子树叶子节点个数
return leafSise(root.left)+leafSise(root.right);
}
5.计算第K层节点个数
核心思想:递归处理 第 k 层节点个数 = 左子树的 k-1 层节点个数 + 右子树的 k-1 层节点个数
eg:
// 求第 K 层节点个数
public static int kLevelSize(Node root, int k){
if(k < 0 || root == null){
return 0;
}
if(k == 1){
return 1;
}
//第 k 层节点个数 = 左子树的 k-1 层节点个数 + 右子树的 k-1 层节点个数
return kLevelSize(root.left,k-1) + kLevelSize(root.right,k-1);
}
6.在二叉树中查找指定元素
// 在二叉树中查找指定元素
// 存在返回该节点的引用 不存在返回 null
Node find(Node root, char toFind){
if(root == null){
return null;
}
if(root.val == toFind){
return root;
}
// 分别递归的去查找左右子树
Node result = find(root.left,toFind);
if(result != null){
return result;
}
find(root.left,toFind);
return find(root.right,toFind);
}