作为菜鸡,首先独立思考半天,结果递归写的有问题,只能先搞出来迭代::
/**
* 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;
Queue<TreeNode> queue=new LinkedList<>();
int ans=0;
queue.offer(root);
while(!queue.isEmpty()){
int len=queue.size();
for(int i=0;i<len;i++){
ans++;
TreeNode temTree=queue.poll();
if(temTree.left!=null) queue.offer(temTree.left);
if(temTree.right!=null) queue.offer(temTree.right);
}
}
return ans;
}
}
再来根据学习思考大佬的理解以后写的递归:
每次都是差一点写出来。可是这一点需要再学好久估计才能真正掌握
/**
* 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) {
return getCount(root);
}
int getCount(TreeNode root){
if(root==null) return 0;
int leftCount=getCount(root.left);
int rightCount=getCount(root.right);
int ans=leftCount+rightCount+1;
return ans;
}
}
因为是完全二叉树,比较特殊,因此除了传统的递归和迭代以外,还有根据完全二叉树的特性做的:
/**
* 针对完全二叉树的解法
*
* 满二叉树的结点数为:2^depth - 1
*/
public int countNodes(TreeNode root) {
if(root == null) {
return 0;
}
int leftDepth = getDepth(root.left);
int rightDepth = getDepth(root.right);
if (leftDepth == rightDepth) {// 左子树是满二叉树
// 2^leftDepth其实是 (2^leftDepth - 1) + 1 ,左子树 + 根结点
return (1 << leftDepth) + countNodes(root.right);
} else {// 右子树是满二叉树
return (1 << rightDepth) + countNodes(root.left);
}
}
private int getDepth(TreeNode root) {
int depth = 0;
while (root != null) {
root = root.left;
depth++;
}
return depth;
}
这篇博客探讨了如何计算二叉树的节点数量,分别使用迭代和递归两种方法实现。首先展示了一个使用队列进行迭代的解决方案,然后通过递归的方式重新实现。此外,针对完全二叉树的特性,还提供了一种更高效的解法,利用完全二叉树的层数关系来减少计算量。博主分享了在实现过程中遇到的挑战和学习心得。
2127

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



