请用java写出递归遍历树,查询并返回某一子节点
时间: 2024-04-13 15:28:24 浏览: 110
当然可以!下面是一个使用递归遍历树并查询并返回某一子节点的Java代码示例:
```java
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public class TreeTraversal {
public static TreeNode findNode(TreeNode root, int target) {
if (root == null || root.val == target) {
return root;
}
TreeNode leftResult = findNode(root.left, target);
if (leftResult != null) {
return leftResult;
}
TreeNode rightResult = findNode(root.right, target);
if (rightResult != null) {
return rightResult;
}
return null;
}
public static void main(String[] args) {
// 构建一个二叉树
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(7);
int target = 5;
TreeNode result = findNode(root, target);
if (result != null) {
System.out.println("找到目标节点 " + target);
} else {
System.out.println("未找到目标节点 " + target);
}
}
}
```
在这个示例中,我们定义了一个`TreeNode`类来表示树的节点。`TreeTraversal`类中的`findNode`方法使用递归来遍历树,并在每个节点上进行目标值的比较。如果找到目标节点,就返回该节点;否则,继续递归遍历左子树和右子树。最后,在`main`方法中,我们创建一个二叉树,并调用`findNode`方法来查找目标节点。
阅读全文
相关推荐















