case1:求任意二叉树节点个数:使用层次遍历,时间复杂度O(n)
class Solution {
public int countNodes(TreeNode root) {
if(root==null)return 0;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(root);
int counts = 0;
while(!queue.isEmpty()){
TreeNode head = queue.poll();
counts++;
if(head.left!=null){
queue.add(head.left);
}
if(head.right!=null){
queue.add(head.right);
}
}
return counts;
}
}
case2:T222求BST节点个数
思想:利用完全二叉树的特性:
求深度:借助完全二叉树的特性来减枝求深度,(若root为完全二叉树则root的深度=其左子树深度+1,也就是Max(leftDepth,rigthDepth)必为leftDepth),且要么leftDepth = rightDepth要么leftDepth = rightDepth+1
求节点数: