完全二叉树的节点个数

这篇博客探讨了如何计算二叉树的节点数量,分别使用迭代和递归两种方法实现。首先展示了一个使用队列进行迭代的解决方案,然后通过递归的方式重新实现。此外,针对完全二叉树的特性,还提供了一种更高效的解法,利用完全二叉树的层数关系来减少计算量。博主分享了在实现过程中遇到的挑战和学习心得。

作为菜鸡,首先独立思考半天,结果递归写的有问题,只能先搞出来迭代::

/**
 * 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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值