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

    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.

    思路:

      分治法的应用

    他人代码:

    public class Solution {
        public int countNodes(TreeNode root) {
            if(root == null)    return 0;
            int h = getHeight(root);
            return getHeight(root.right)==h-1 ? (1<<(h-1)) + countNodes(root.right) : (1<<(h-2)) + +countNodes(root.left);
        }
        public int getHeight(TreeNode root)
        {
            return root==null ? 0 : 1+getHeight(root.left);
        }
    }
    View Code
    • 关键之处在于通过获取高度确定,左子树满了还是没有满,若满了则只需要求解右子树的节点数就可以了,若未满,则需要求解左子树的节点数,典型的分治思想,主要一点在于求解高度进化划分问题成子问题。
    • 最近写代码不想思考啊,这道题本可以自己最初来的,看了别人的代码,浪费了一道这么好的题目。Since I halve the tree in every recursive step, I have O(log(n)) steps. Finding a height costs O(log(n)). So overall O(log(n)^2).
    • 改掉不好的习惯,最近的习惯有点不好,坏习惯有点多。
  • 相关阅读:
    (最小路径覆盖) poj 1422
    (匈牙利算法) hdu 2119
    (匈牙利算法) hdu 4185
    (匈牙利算法) hdu 2063
    (匈牙利算法)hdu 1281
    (匈牙利算法DFS)hdu 3729
    (01 染色判奇环) hdu 3478
    (多重背包)poj 1276
    (判断欧拉回路)poj 1368
    (差分约束) hdu 1384
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4581317.html
Copyright © 2011-2022 走看看