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
来源:CSDN
原文:https://blog.csdn.net/dongqifan/article/details/36032873
版权声明:本文为博主原创文章,转载请附上博文链接!

最新文章

  1. Log4j 用法
  2. Spring-Context之三:使用XML和Groovy DSL配置Bean
  3. No.002:Add Two Numbers
  4. ArcGIS API for JavaScript Beta初步试探(一)
  5. 7、XML加强/Web开发/Tomcat
  6. linux学习建议
  7. strtr介绍
  8. 【ufldl tutorial】Softmax Regression
  9. 使用WebMatrix发布网站到Windows Azure
  10. c 深度剖析 2
  11. HDU ACM 1325 / POJ 1308 Is It A Tree?
  12. C# word开发
  13. acm位运算应用 搜索
  14. table强制不换行
  15. 解决方案-Microsoft Visual Studio 2012 已停止工作
  16. qt 4.6.2 vs 2005 + QCreator 开发环境配置(有注册码)
  17. 关于在用Swift开发iOS时如何隐藏NavigationBar和TabBar
  18. Response.Redirec方法传递汉字出现乱码
  19. srm 534
  20. window对象的属性

热门文章

  1. configparser logging
  2. Unity 3D 使用Relief Terrain Pack(RTP) 问题
  3. NYOJ-768移位密码,最简单的代替密码;
  4. [luoguP1972] [SDOI2009]HH的项链(莫队 || 树状数组 || 主席树)
  5. hrbust 1840 (树状数组第k大) 删点使用
  6. 餐巾(cogs 461)
  7. 2018/2/18 SpringCloud Eureka的学习和spirng ribbon的部分源码追踪
  8. 从零开始写STL—栈和队列
  9. POJ 2101 Intervals 差分约束
  10. 深入理解hadoop(二)