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 2hnodes inclusive at the last level h.

    题目大意:给定一个完全二叉树,返回这个二叉树的节点数量。

    解题思路:一开始想着层次遍历,O(n),结果TLE,后来优化了下,采用递归的方式来做,总节点数等于1+左子树的数量+右子树的数量,因为是完全二叉树,所以对于子树是满二叉树的可以直接计算出结果并返回。

    public class Solution {
        public int countNodes(TreeNode root) {
            if(root==null){
                return 0;
            }
            TreeNode left =root,right=root;
            int cnt = 0;
            while(right!=null){
                left=left.left;
                right=right.right;
                cnt++;
            }
            if(left==null){
                return (1<<cnt)-1;
            }
            return 1+countNodes(root.left)+countNodes(root.right);
        }
    }
  • 相关阅读:
    hdu 1225大水题
    hdu2102广搜
    hdu1403 赤裸裸的后缀数组
    hdu 1526 poj 1087最大流
    hdu 1557暴力枚举
    hdu 1240广搜
    hdu4416 后缀数组
    hdu1113大水题
    hdu2222赤裸裸的DFA
    hdu4476水题
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4599696.html
Copyright © 2011-2022 走看看