zoukankan      html  css  js  c++  java
  • Count Complete Tree Nodes -- LeetCode

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

    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.

    思路:解决这个问题,我们首先要获得树的最大深度。对于一颗空的树,其深度为-1,对于只有一个根节点的树,其深度为0,以此类推。

    之后,我们比较左子树和右子树的深度。这里只有两种情况,两颗子树的深度相等,或者左子树的深度比右子树的深度大1。

    • 当两颗子树深度相等时,我们知道当前这棵树最底层的叶子结点在两棵子树中都有,因此左子树是完全二叉树。于是我们可以根据深度计算出左子树的节点数加1(包含当前树的根节点),然后通过递归计算右子树的节点数。
    • 当两颗深度不想等时,我们知道当前这棵树最底层的叶子结点只在左子树中,因此右子树是完全二叉树。于是我们可以根据深度计算出右子树的节点数加一(包含当前树的根节点),然后通过递归计算左子树的节点数。

    我们最多进行O(logn)次递归,每次递归时都需要计算深度,复杂度O(logn),总复杂度是O(logN*logN)。

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int depth(TreeNode* root) {
    13         return root == NULL ? -1 : 1 + depth(root->left);
    14     }
    15     int countNodes(TreeNode* root) {
    16         int dep = depth(root);
    17         if (dep < 1) return dep + 1;
    18         int rightChildDepth = depth(root->right);
    19         if (dep == rightChildDepth + 1) return (1 << dep) + countNodes(root->right);
    20         return (1 << (rightChildDepth + 1)) + countNodes(root->left);
    21     }
    22 };
  • 相关阅读:
    了解HTTP Header之User-Agent和HTTP协议的响应码
    怎样才算一个优秀的管理者
    ldpi、mdpi、hdpi、xhdpi、xxhdpi (无内容,待填)
    手把手教做小偷采集
    java中碰到无法解决的问题:无法访问类的getter访问器
    简单的加密解密处理
    Java中处理二进制移位
    Java中实现String.padLeft和String.padRight
    这短短几行代码价值一万
    从一篇文章中检查特定单词出现数量和第一次出现位置
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5789546.html
Copyright © 2011-2022 走看看