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;
        }
    }
  • 相关阅读:
    整数的溢出或回绕
    C语言每日一题
    C语言刷“矩阵”类题目(2维矩阵/2级指针)
    C语言刷2数/3数/4数之和
    C语言刷数组题记录
    二、IAR创建工程并进行烧写
    三、STM8的学习笔记-----GPIO操作
    51单片机--------如何使用keil软件建立一个工程
    一、搭建mosquitto
    二、解决端口占用被占用情况
  • 原文地址:https://www.cnblogs.com/TinyBobo/p/4588175.html
Copyright © 2011-2022 走看看