222. Count Complete Tree Nodes

Given a complete binary tree, count the number of nodes.

Note:

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

Example:

Input: 
    1
   / \
  2   3
 / \  /
4  5 6

Output: 6

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-complete-tree-nodes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

完全二叉树的节点数

一、遍历所有节点

二、这是完全二叉树,如果他是一个满二叉树,那么节点数 = 2 ^ 高度 - 1。此时可以判断根节点的左子树或者右子树是不是满二叉树。

判断方法,求出左子树的高度(只用判断跟节点到最左边的节点的高度),如果左子树的高度等于右子树的高度,那说明左子树一定是满二叉树,右子树不一定是满二叉树,那么左子树的节点可以用 2 ^ 高度 - 1计算出,右子树继续遍历。

class Solution {
    public int getLeftHight (TreeNode node){
        if (node.left == null) {
            return 1;
        }
        return getLeftHight(node.left) + 1;
    }
    public int countNodes(TreeNode root) {
        int ans = 1;
        if (root == null) {
            return 0;
        }
        if (root.left == null) {
            return 1;
        }
        if (root.right == null) {
            return 2;
        }
        int leftLen = getLeftHight(root.left);
        int rightLend = getLeftHight(root.right);
        if (leftLen == rightLend) {
            ans += (1 << leftLen) - 1;
            ans += countNodes(root.right);
        } else {
            ans += countNodes(root.left);
            ans += countNodes(root.right);
        }
        return ans;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值