您的位置:首页 > 其它

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

2014-06-30 20:34 239 查看
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);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: