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


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

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