1、求二叉树的节点个数
1). 遍历二叉树,遇到每个节点加一;
private static int treeSize = 0;
private static void size(Node root) {
if (root == null) {
return;
}
treeSize++;
size(root.left);
size(root.right);
}
2). 二叉树总结点个数 = 根节点 + 左子树节点个数 + 右子树节点个数
private static int size(Node root) {
if (root == null) {
return 0;
}
return 1 + size(root.left) + size(root.right);
}
2、二叉树的叶子节点
方法一
private static int leafSize = 0;
private static void LeafSize(Node root){
if (root == null) {
return;
}
// 当该节点的左节点和右节点为空时,为叶子节点
if (root.left == null && root.right == null) {
leafSize++;
return;
}
LeafSize(root.left);
LeafSize(root.right);
}
方法二
private static int leafSize(Node root) {
// 空树
if(root == null) {
return 0;
}
if(root.right == null && root.left == null) {
return 1;
}
return leafSize(root.left) + leafSize(root.right);
}
3、求二叉树第 K 层的节点个数
分析: 第 K 层节点个数 = 左子树 (K - 1) 层节点个数 + 右子树 (K - 1)层节点个数
private static int kLevelSize(Node root,int k) {
if(root == null || k <= 0) {
return 0;
}
// K 为第一层
if(k == 1) {
return 1;
}
// 不是第一层
// k 层节点个数 = 左子树 k-1 层节点个数 + 右子树 k-1 层节点个数
return kLevelSize(root.left,k-1)+kLevelSize(root.right,k-1);
}
4、判断元素是否在二叉树中
分析:遍历二叉树,当节点值等于该元素,则返回该节点,否则为null;
方法一 :
private static Node result = null;
private static void find(Node root, char toFInd) {
if(root == null) {
return;
}
if(root.val == toFInd) {
result = root;
return;
}
find(root.left,toFInd);
find(root.right,toFInd);
}
方法二:
private static 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;
}
// 如果左子树中没有找到。就在右子树中找,并返回结果
return find(root.right, toFind);
}