题解 | #统计农场牛数量#
统计农场牛数量
https://www.nowcoder.com/practice/c18924a6debf437180d77baec91dc586
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
public int countNodes (TreeNode root) {
if(root == null) return 0;
TreeNode l = root, r = root;
int lc = 0, rc = 0;
//左边的深度
while(l != null){
lc++;
l = l.left;
}
//右边的深度
while(r != null){
rc++;
r = r.right;
}
//如果左右两边的深度都相等,则该树为完全二叉树
if(lc == rc) return (int)Math.pow(2,lc)-1;
return 1+countNodes(root.left)+countNodes(root.right);
}
}
查看8道真题和解析