zoukankan      html  css  js  c++  java
  • LeetCode_222.完全二叉树的节点个数

    给出一个完全二叉树,求出该树的节点个数。

    说明:

    完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。

    示例:

    输入: 
        1
       / 
      2   3
     /   /
    4  5 6
    
    输出: 6

    C#代码

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left;
     *     public TreeNode right;
     *     public TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        /*深度字典,用于减少深度遍历次数。*/
        private Dictionary<TreeNode,int> dic = new Dictionary<TreeNode,int>();
        private int NodeLevel(TreeNode root){
            if(root == null) return 0;
            if(dic.ContainsKey(root)) return dic[root];
            
            int level = NodeLevel(root.left) + 1;
            dic.Add(root, level);
            
            return level;    
        }
        public int CountNodes(TreeNode root) {
            if(root == null) return 0;
            
            /*计算左右子树的深度*/
            int leftLevel = NodeLevel(root.left);
            int rightLevel = NodeLevel(root.right);
    
            /*左右子树高度谁高谁为满二叉树,另一子树未完全二叉树。高度h的满二叉树,节点总数为2^h-1;*/
            if(leftLevel == rightLevel) return (1 << leftLevel) + CountNodes(root.right);
            return (1 << rightLevel) + CountNodes(root.left);
        }
    }
    
  • 相关阅读:
    24、合并两个有序链表
    23、反转链表
    22、删除链表的倒数第N个节点
    21、删除链表中的节点
    18、实现strStr()
    17、字符串转换整数 (atoi)
    15、有效的字母异位词
    16、验证回文字符串
    14、字符串中的第一个唯一字符
    mybatis入门(七)----延迟加载
  • 原文地址:https://www.cnblogs.com/fuxuyang/p/14244567.html
Copyright © 2011-2022 走看看