码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-10-31 20:14:44      阅读:368      评论:0      收藏:0      [点我收藏+]

标签:for   new   https   链接   param   value   package   版权   节点   


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
版权声明:本文为博主原创文章,转载请附上博文链接!

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

标签:for   new   https   链接   param   value   package   版权   节点   

原文地址:https://www.cnblogs.com/ExMan/p/9885047.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!