zoukankan      html  css  js  c++  java
  • 打印二叉树中距离根节点为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
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    python之名称空间
    python之对象(实例)
    python之类
    python之类和对象
    python之面向对象的程序设计
    python之函数联系
    Python之函数第三篇
    python之列表和生成器表达式篇
    网络基本概念
    Git
  • 原文地址:https://www.cnblogs.com/ExMan/p/9885047.html
Copyright © 2011-2022 走看看