LeetCode222. 完全二叉树的节点个数

版权声明: https://blog.csdn.net/weixin_40550726/article/details/82987069

给出一个完全二叉树,求出该树的节点个数。

说明:

完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。

示例:

输入: 
    1
   / \
  2   3
 / \  /
4  5 6

输出: 6

思路:首先想到遍历二叉树,计数所有二叉树结点,但该算法会超出时间限制。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int countNodes(TreeNode root) {
         int count=0;
        if(null==root){
            return count;
        }
        ArrayDeque<TreeNode> queue=new ArrayDeque<TreeNode>();
        queue.add(root);
        while(!queue.isEmpty()){
            TreeNode node=queue.removeFirst();
            count++;
            if(null!=node.left){
                queue.add(node.left);
            }
            if(null!=node.right){
                queue.add(node.right);
            }
        }
        return count;
    }
}

解法二:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

     /**
     * 判断一棵树是否是满二叉树
     * 二叉树的最左边的叶子结点的深度如果等于最右边的叶子结点的深度,是满二叉树
     * 是的话返回满二叉树的结点数
     * 否的话再判断该结点的左子树以及右子树是否是满二叉树
     * @param root
     * @return
     */
    public int countNodes(TreeNode root) {
         if(null==root){
            return 0;
        }
        int leftDepth=1;//最左边的叶子结点深度
        int rightDepth=1;//最右边的叶子结点的深度
        TreeNode tmp=root;
        while (null!=tmp.left){
            leftDepth++;
            tmp=tmp.left;
        }
        tmp=root;
        while (null!=tmp.right){
            rightDepth++;
            tmp=tmp.right;
        }
        if(leftDepth==rightDepth){  //是满二叉树
            //满二叉树结点数  n=2^h-1  [n]结点数 [h]满二叉树深度
            return (int) (Math.pow(2,leftDepth)-1);
        }
        return countNodes(root.left)+countNodes(root.right)+1;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40550726/article/details/82987069
今日推荐