直接遍历
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
public class Solution {
public int nodeNum(TreeNode head) {
if (head == null){
return 0;
}
return 1 + nodeNum(head.left) + nodeNum(head.right);
}
}
使用满二叉树的性质
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
public class Solution {
public int nodeNum(TreeNode head) {
if (head == null){
return 0;
}
int left = getHeight(head.left);
int right = getHeight(head.right);
if (left != right){
return (int)Math.pow(2, right) + nodeNum(head.left);
}
return (int)Math.pow(2, left) + nodeNum(head.right);
}
private int getHeight(TreeNode node){
TreeNode cur = node;
int res = 0;
while (cur != null){
cur = cur.left;
res++;
}
return res;
}
}

该博客介绍了两种计算满二叉树节点数的方法:一种是通过递归遍历整个树,另一种利用满二叉树的性质快速计算。详细解析了代码实现过程,包括左右子树高度的获取,以及如何根据高度快速计算节点总数。
1518

被折叠的 条评论
为什么被折叠?



