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

求二叉树第k层的结点个数

时间:2017-01-24 12:26:21      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:create   poll   pre   numbers   stat   evel   offer   root   created   

tag: 二叉树 - 层次遍历

 思路: 用层次遍历思路求解

 辅助: 队列

 

package com.zhaochao.tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by zhaochao on 17/1/23.
 */
public class NodesNumberKLevel {

    public int getNodesNumberKLevel(TreeNode root, int k) {

        int count = 0;
        if(root == null || k <= 0 || k > getDepthOfTree(root)) {
            return count;
        }
        if(k == 1) {
            return 1;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        while(!queue.isEmpty()) {
            int size = queue.size();
            if(count == k - 1) {
                return size;
            }
            ArrayList<Integer> level = new ArrayList<Integer>();
            for(int i = 0; i < size; i++) {
                TreeNode head = queue.poll();
                level.add(head.val);
                if(head.left != null) {
                    queue.offer(head.left);
                }
                if(head.right != null) {
                    queue.offer(head.right);
                }
            }
            count++;
        }
        return count;
    }

    public int getDepthOfTree(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int left = getDepthOfTree(root.left);
        int right = getDepthOfTree(root.right);
        return Math.max(left,right) + 1;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(0);
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);

        root.left = node1;
        root.right = node2;
        node2.left = node3;

        NodesNumberKLevel test = new NodesNumberKLevel();
        int numbers = 0;
        numbers = test.getNodesNumberKLevel(root, 3);
        System.out.println("The numbers of nodes of level 3 is : " + numbers);
    }
}

  

求二叉树第k层的结点个数

标签:create   poll   pre   numbers   stat   evel   offer   root   created   

原文地址:http://www.cnblogs.com/superzhaochao/p/6346824.html

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