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).
  • 改掉不好的习惯,最近的习惯有点不好,坏习惯有点多。

posted on 2015-06-16 17:04  zhouzhou0615  阅读(192)  评论(0编辑  收藏  举报

导航