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;
        }
    }
  • 相关阅读:
    洛谷P1422 小玉家的电费
    洛谷P1425 小鱼的游泳时间
    洛谷P1421 小玉买文具
    洛谷P1001 A+B Problem
    洛谷P1000 超级玛丽游戏
    Android Hook框架adbi的分析(2)--- inline Hook的实现
    Android Apk加固的初步实现思路(dex整体加固)
    Android Hook框架adbi的分析(1)---注入工具hijack
    从苏宁电器到卡巴斯基(后传)第05篇:聊聊我对WannaCry产生的感慨
    Android APK程序的smali动态调试
  • 原文地址:https://www.cnblogs.com/TinyBobo/p/4588175.html
Copyright © 2011-2022 走看看