打印二叉树中距离根节点为k的所有节点

本文介绍了一种算法,用于在给定树的根节点和整数k的情况下,打印所有距离根节点k距离的节点。通过递归遍历左子树和右子树,当k减至0时打印当前节点的值,实现了对特定距离节点的有效检索。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


package tree;

public class Printnodesatkdistancefromroot {

/**
* Given a root of a tree, and an integer k. Print all
* the nodes which are at k distance from root.
For example, in the below tree, 4, 5 & 8 are at distance 2 from root.
1
/ \
2 3
/ \ /
4 5 8
* @param args
*/
public static void printk(TreeNode root,int k){
if(k<0||root==null){
return;
}
if(k==0){
System.out.print(root.value+" ");
return;
}
printk(root.left, k-1);
printk(root.right, k-1);
}
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(8);
printk(root, 2);

}

---------------------
作者:dongqifan
来源:优快云
原文:https://blog.youkuaiyun.com/dongqifan/article/details/36032873
版权声明:本文为博主原创文章,转载请附上博文链接!

转载于:https://www.cnblogs.com/ExMan/p/9885047.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值