Java给出代码 判定二叉树中是否有值为x的元素
时间: 2024-03-11 22:47:18 浏览: 19
可以使用递归的方式来判断二叉树中是否有值为x的元素。具体实现如下:
```java
public boolean containsX(TreeNode root, int x) {
if (root == null) {
return false;
}
if (root.val == x) {
return true;
}
return containsX(root.left, x) || containsX(root.right, x);
}
```
其中,`TreeNode`是二叉树节点的定义,包含`val`、`left`和`right`三个属性。`containsX`方法接收一个二叉树的根节点`root`和一个要查找的值`x`,返回一个布尔值表示是否存在值为`x`的节点。
方法的实现非常简单,首先判断当前节点是否为null,如果是直接返回false;如果当前节点的值等于x,返回true;否则递归地在左右子树中查找是否存在值为x的节点,只要左右子树中有一个存在,就返回true,否则返回false。
相关问题
写出C语言代码在二叉树查找是否存在值为x的结点
当然,我可以为你提供代码。请看下面:
```
#include <stdio.h>
#include <stdlib.h>
struct node
{
int key;
struct node *left, *right;
};
// 创建新节点并返回
struct node* newNode(int item)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// 二叉树查找
struct node* search(struct node* root, int key)
{
if (root == NULL || root->key == key)
return root;
if (root->key < key)
return search(root->right, key);
return search(root->left, key);
}
// 插入节点
struct node* insert(struct node* node, int key)
{
if (node == NULL) return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
return node;
}
// 打印中序遍历结果
void inorder(struct node* root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}
// 主程序
int main()
{
struct node* root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
printf("中序遍历结果:\n");
inorder(root);
printf("\n");
int x = 40;
struct node* result = search(root, x);
if(result)
{
printf("%d存在于二叉树中\n", x);
}
else
{
printf("%d不在二叉树中\n", x);
}
return 0;
}
```
这个代码基本上是一个二叉查找树的模板,它能够插入节点、进行中序遍历、查找特定节点。你可以将其中的节点值改为自己想要查找的值,修改一下就可以使用了。
求二叉树中以元素值为x的结点为根的子树的深度
要求二叉树中以元素值为x的结点为根的子树的深度,可以通过遍历二叉树来实现。具体步骤如下:
1. 从根节点开始遍历二叉树,如果当前节点的值等于x,则以该节点为根的子树深度为1,返回1。
2. 如果当前节点的值不等于x,则分别递归遍历该节点的左子树和右子树,得到左子树和右子树以x为根的子树深度。
3. 取左子树和右子树以x为根的子树深度的最大值,加1即为以x为根的子树深度。
4. 返回以x为根的子树深度。
代码实现如下:
```
int getDepth(TreeNode* root, int x) {
if (root == NULL) {
return ;
}
if (root->val == x) {
return 1;
}
int leftDepth = getDepth(root->left, x);
int rightDepth = getDepth(root->right, x);
if (leftDepth > rightDepth) {
return leftDepth + 1;
} else {
return rightDepth + 1;
}
}
```