zoukankan      html  css  js  c++  java
  • [LeetCode-JAVA] 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 2hnodes inclusive at the last level h.

    题意:求一个完全二叉树的节点个数。

    思路:找到最后一层的最后一个节点,可以判断左右节点最最左边的层数是否相同,如果相同,则左子树为满二叉树,若不同则右子树为满二叉树。

    其中在求解的过程中,需要用到幂次的运算,如果用Math.pow会超时,可以考虑有位操作,但是要考虑2的0次幂的特殊情况。

    代码:

    public class Solution {
        public int countNodes(TreeNode root) {
            if(root == null)
                return 0;
            int left = countLevel(root.left);
            int right = countLevel(root.right);
            
            int leftpow = 2<<(left-1);
            int rightpow = 2<<(right-1);
            
            if(left == 0)   //0次幂,<<不出来
                leftpow = 1;
            if(right == 0)
                rightpow = 1;
            
            if(left == right){
                return leftpow + countNodes(root.right);
            }else
                return rightpow + countNodes(root.left);
        }
        
        public int countLevel(TreeNode root) {
            if(root == null)
                return 0;
            int count = 0;
            while(root != null) {
                count++;
                root = root.left;
            }
            
            return count;
        }
    }

    后来想了一下,有个小技巧,因为要用到2的0次幂,可以用1的1次幂来表示,因此可以将位操作换成( 1<< ) 可以大大精简代码。

    代码:

    public class Solution {
        public int countNodes(TreeNode root) {
            if(root == null)
                return 0;
            int left = countLevel(root.left); 
            int right = countLevel(root.right);
            
            if(left == right){
                return (1<<left) + countNodes(root.right);
            }else
                return (1<<right) + countNodes(root.left);
        }
        
        public int countLevel(TreeNode root) {
            if(root == null)
                return 0;
            int count = 0;
            while(root != null) {
                count++;
                root = root.left;
            }
            
            return count;
        }
    }
  • 相关阅读:
    linux重新编译内核
    无废话ubuntu 13.4w文件共享配置
    VB6关于判断模态窗体的问题
    在.NET中快速创建一个5GB、10GB或更大的空文件
    利用虚拟光驱实现 将WINDOWS文件供虚拟机中的UBUNTU共享
    论这场云盘大战,以及各网盘的优劣
    struts2 全局格式化,格式化时间,金钱,数字
    SQL SERVER 2000/2005/2008数据库数据迁移到Oracle 10G细述
    女攻城师走在移动互联网道路的这两年
    用正则匹配多行文本
  • 原文地址:https://www.cnblogs.com/TinyBobo/p/4588175.html
Copyright © 2011-2022 走看看