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

    题目:

    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:

    暴力解决,遍历树的所有节点,依次统计。

    会超时,题目限定了该二叉树是完全二叉树,该种思路适用于所有二叉树。

    思路2:

    暴力解决无法测试通过,此时需要考虑完全二叉树的特点。

    完全二叉树,至少有一课子树是完美二叉树,另一课子树至少是完全二叉树。

    因此可以递归的计算。

    判断完美二叉树:

         最内侧的叶子结点和最外侧的叶子结点是否在同一层。

    代码:

     1     public static int countNodes(TreeNode root){
     2         if(root == null){
     3             return 0;
     4         }
     5         
     6         int hl = getLeft(root)+1;
     7         int hr = getRight(root)+1;
     8         
     9         if(hl == hr){
    10             int num = (2<<(hl-1))-1;
    11             return num;
    12         }else{
    13             return countNodes(root.left)+countNodes(root.right)+1;
    14         }
    15     }
    16 
    17     public static int getRight(TreeNode root) {
    18         int cou = 0;
    19         TreeNode ptr = root;
    20         while(ptr.right != null){
    21             cou++;
    22             ptr = ptr.right;
    23         }
    24         return cou;
    25     }
    26 
    27     public static int getLeft(TreeNode root) {
    28         int cou = 0;
    29         TreeNode ptr = root;
    30         while(ptr.left != null){
    31             cou++;
    32             ptr = ptr.left;
    33         }
    34         return cou;
    35     }
  • 相关阅读:
    [字符串] 洛谷 P2264 情书
    [IDA*] 洛谷 P2324 骑士精神
    [Tarjan] 洛谷 P2746 校园网
    [dp][瞎搞] 洛谷 P2501 数字序列
    [虚树][lca][dfs] 洛谷 P3233 世界树
    [斜率优化][dp] 洛谷 P3648 序列分割
    [带修莫队] Bzoj 2120 数颜色
    [数学][组合数] Jzoj P4257 着色
    [贪心][前缀和] Jzoj P4256 平均数
    [dfs] 洛谷 P2535 收集资源
  • 原文地址:https://www.cnblogs.com/bywallance/p/5569483.html
Copyright © 2011-2022 走看看