题目:求二叉树第k层节点的个数:
思路:
1. 递归:求根为root的二叉树第k层节点的个数,就是要求 root.left第k-1层节点的个数+ root.right第k-1层节点的个数
public static int getNumberOfKLevel(TreeNode root,int k){ if(root == null || k <1) return 0; if(k == 1) return 1; int numLeft = getNumberOfKLevel(root.left,k-1); int numRight = getNumberOfKLevel(root.right,k-1); return numLeft+numRight; }
2.迭代:利用队列,相当于求二叉树的高度,只是求到哪一层的高度而已
public static int getNumberOfLevelK(TreeNode root,int k){ if(root == null || k <1) return 0; if(k == 1) return 1; Queuequeue = new LinkedList (); int num = 1; int currentLevelNum = 0; queue.add(root); while(k >1){ while(num > 0){ TreeNode node = queue.remove(); if(node.left != null){ queue.add(node.left); currentLevelNum++; } if(node.right != null){ queue.add(node.right); currentLevelNum++; } num --; } num = currentLevelNum; k--; } return queue.size(); }