二叉树:
链式表示法:
利用树的结点表示二叉树,类似链表
class Node{
int val;
Node left; //左孩子,左子树的根
Node right; //右孩子,右子树的根
}
递归方法:
1.找递推公式
2.找终止条件
求叶子结点的个数:
private static int leafSize = 0;
private static void getLeafSize(Node root) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
leafSize++;
}
getLeafSize(root.left);
getLeafSize(root.right);
}
public static int getLeafSize2(Node root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
int left = getLeafSize2(root.left);
int right = getLeafSize2(root.right);
return left + right;
}
求二叉树的高度:
public static int getHeight(Node root) {
if (root == null) {
return 0;
}
int left = getHeight(root.left);
int right = getHeight(root.right);
return Math.max(left, right) + 1;
//return Math.max(getHeight(root.left),getHeight(root.right))+1;
}
求二叉树第k层结点的个数:
汇总:
1.利用递归求左子树第 k -1 层的结点个数:left
2.利用递归求右子树第 k -1 层的结点个数:right
3.整棵树第 k 层的结点个数 = left + right
出口:
1.root == null return 0;
2.root != null && k =1 return 1;
public static int getKLevel(Node root, int k) {
if (root == null) {
return 0;
}
if (k == 1) {
return 1;
}
return getKLevel(root.left, k - 1) + getKLevel(root.right, k - 1);
}
查找 val 所在结点:
// 查找 val 所在结点,没有找到返回 null
// 按照 根 -> 左子树 -> 右子树的顺序进行查找
// 一旦找到,立即返回,不需要继续在其他位置查找
public static Node find(Node root, int val) {
if (root == null) {
return null;
}
if (root.val == val) {
return root;
}
Node n = find(root.left, val);
if (n != null) {
return n;
}
n = find(root.right, val);
if (n != null) {
return n;
}
return null;
}
public static boolean find2(Node root, int val) {
if (root == null) {
return false;
}
if (root.val == val) {
return true;
}
if (find2(root.left, val)) {
return true;
}
return find2(root.right, val);
}
public static boolean find3(Node root, int val) {
return root != null
&& (
root.val == val
|| find3(root.left, val)
|| find3(root.right, val)
);
}
完!
转载:https://blog.csdn.net/weixin_44772874/article/details/102015550
查看评论