• [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;
        }
    }
  • 相关阅读:
    0是字符串的终止符
    c语言中获取数组的长度写法
    c语言第一个程序
    linux下adb连接不上解决方法
    android的apk权限查看
    dumpsys netpolicy中state的含义
    查看ps和dumpsys netpolicy
    批量安装/卸载手机apk--python语言
    【转载】Think as Customer 以客户为中心的测试理念
    利用xampp进行https操作
  • 原文地址:https://www.cnblogs.com/TinyBobo/p/4588175.html
Copyright © 2020-2023  润新知