• 完全二叉树节点个数


    1、没利用完全二叉树性质的递归

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        Queue<TreeNode> q = new LinkedList<>();
        public int countNodes(TreeNode root) {
        if(root == null) return 0;    
        return countNodes(root.left) + countNodes(root.right) + 1;
            
        }
    }
    
    

    2、因为完全二叉树只有最后一层不是满的。
    1.1、左子树不是满二叉树,右子树自然就是满二叉树了

    1.2、左子树是满二叉树,右子树不一定。

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    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 countNodes(root.right) + (1<<left);//左子树加上根节点数目刚好是2^left,用位运算快一点
            }else{
                return countNodes(root.left) + (1<<right);//同理
            }
        }
        private int countLevel(TreeNode root){//可以帮助判断是否左子树是满二叉树
            int level = 0;
            while(root != null){
                level++;
                root = root.left;
            }
            return level;
        }
    }
    
    
    不一样的烟火
  • 相关阅读:
    短信猫软件的实现(C#)<八>7bitPDU的解码
    短信猫软件的实现(C#)<七>短信猫(简化测试版)实现
    短信猫软件的实现(C#)<十一>软件实现(完结篇)
    我的EDA课程设计 Verilog HDL 自动售票机的实现
    Linux JNI(1)
    Notes
    Linux 线程属性
    Linux shared lib
    Linux 几个调试命令
    Java工具
  • 原文地址:https://www.cnblogs.com/cstdio1/p/13339047.html
Copyright © 2020-2023  润新知