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;
        }
    }
  • 相关阅读:
    Spring Boot学习笔记
    打造高效率的软件测试
    如何将测试结果在jenkins上发布
    如何在docker container中运行web自动化测试
    Jmeter中随机读取测试文件的内容
    如何提高UI自动化测试的质量
    mac系统上添加定时任务
    keypass口令管理实践
    GPG实践
    树的遍历
  • 原文地址:https://www.cnblogs.com/TinyBobo/p/4588175.html
Copyright © 2011-2022 走看看