Count Complete Tree Nodes ---LeetCode

https://leetcode.com/problems/count-complete-tree-nodes/

解题思路:

题目要求计算一棵完全二叉树的节点数。首先回顾一下完全二叉树:

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 2^h nodes at the last level h.(via Wikipedia)

完全二叉树是指除了最后一层,其余每层的节点都填满,最后一层的节点尽可能的靠左边, 并且可能有的节点数是 [1 - 2^h] 个。

解这道题分以下几个步骤:
- 计算左子树的高度
- 计算右子树的高度
- 如果左子树的高度等于右子树的高度,那么说明这是一颗满二叉树,总的节点就是 2^h - 1。
- 如果两个高度不相等,那么就递归计算左右子树的节点数。

时间复杂度是 O(h^2),h是树的高度。

注意:if (left == right) return (2 << (left - 1)) - 1; 2^h - 1 的计算。

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

        int left  = getLeftHeight(root) + 1;
        int right = getRightHeight(root) + 1;

        if (left == right) 
            return (2 << (left - 1)) - 1;
        else               
            return countNodes(root.left) + countNodes(root.right) + 1;
    }
    public int getLeftHeight(TreeNode root) {
        if (root == null) return 0;
        int height = 0;
        while (root.left != null) {
            height++;
            root = root.left;
        }
        return height;
    }
    public int getRightHeight(TreeNode root) {
        if (root == null) return 0;
        int height = 0;
        while (root.right != null) {
            height++;
            root = root.right;
        }
        return height;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值