提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
计算二叉树的节点个数,计算满二叉树的节点个数,计算完全二叉树的节点个数
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int countNodes(TreeNode root) {
if(root == null){
return 0;
}
return 1 + countNodes(root.left) + countNodes(root.right);
}
}
更高效的解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int countNodes(TreeNode root) {
if(root == null){
return 0;
}
TreeNode l = root, r = root;
int low = 0, high = 0;
while(l != null){
l = l.left;
low ++;
}
while(r != null){
r = r.right;
high ++;
}
if(low == high){
return (int)Math.pow(2, low) - 1;
}
return 1 + countNodes(root.left) + countNodes(root.right);
}
}