输出单层节点

输出单层结点

http://www.nowcoder.com/questionTerminal/cb6c883b123b44399377d0c71e6ba3ea

层次遍历应用

import java.util.*;

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}*/
public class TreeLevel {
    public ListNode getTreeLevel(TreeNode root, int dep) {
        // write code here
        LinkedList<TreeNode> q = new LinkedList<>();
        q.offer(root);
        ListNode head = new ListNode(0);
        ListNode cur = head;
        int count = 0;
        while( !q.isEmpty()){
            int size = q.size();
            count++;
            for(int i = 0; i< size;++i){
                root = q.poll();
                 if(count == dep){
                     cur.next = new ListNode(root.val);
                     cur = cur.next;
                 }
                if(root.left != null){
                    q.offer(root.left);
                }
                if(root.right != null){
                    q.offer(root.right);
                }
            }
        }
        return head.next;
    }
}
全部评论

相关推荐

当初高考报计算机真是造大孽了啊!卷的飞起!哪都是计算机的人,考研,考公,找工作全他奶的计算机的人,太难了。国企也是。关键一届比一届卷,造大孽了!
_Lyrics_:因为计算机,没有体验到快乐的大学研究生时光,好不容易修完课程就要出去实习,看着别人专业可以一起搓麻将,游山玩水,而我却要自己一个人住在北上不到十平米的出租屋,每天两点一线
点赞 评论 收藏
分享
牛客ID:561366855:期望薪资多少?难以相信这简历找不到工作。说明二本电子信息专业想对口就业非常难。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务