给你一棵 完全二叉树 的根节点 root
,求出该树的节点个数。
递归遍历1
public static int countNodes(TreeNode root){
return preorder(root);
}
//计算树的节点个数
public static int preorder(TreeNode root){
int count=0;
if(root==null) return 0;
int left=preorder(root.left);
int right=preorder(root.right);
count=left+right+1; //树的节点个数=左子树节点个数+右子树节点个数+1(根节点)
return count;
}
递归遍历2(精简版)
public int countNodes(TreeNode root) {
if(root == null) {
return 0;
}
return countNodes(root.left) + countNodes(root.right) + 1;
}