zoukankan      html  css  js  c++  java
  • leetcode-222完全二叉树的节点个数

    题目

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

    说明:

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

    示例:

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

    输出: 6

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/count-complete-tree-nodes
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    最容易想到的实现,计算出左子树的节点个数,计算出右子树的节点个数,然后两个结果相加再加上根节点个数。

    代码:

    /**
     * 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;
            }
        return countNodes(root.left)+countNodes(root.right)+1;    
        }
    

    第二种方法:第一种方法虽然实现简单,但是没有用到题目所给出的完全二叉树的特点,完全二叉树最后一层如果没填满,那么节点都集中在左边,并且其余层的节点都是满的。所以,如果左子树的深度就和右子树的深度相等,那么左子树是满二叉树,那么,反过来,两者深度不等,那么右子树就是完全二叉树,需要计算出左子树的节点个数。完全二叉树的节点个数等于2^n-1

    /**
     * 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 = getDepth(root.left); //获取左子树的深度
            int right = getDepth(root.right); //获取右子树的深度
            int res = 0;
            if(left==right){ // 如果左子树深度和右子树深度相等,说明左子树最底层的节点已满既是 2的n次方 n代表左子树的深度
                res = countNodes(root.right)+(1<<left);
            }else{ // 如果不相等,右子树的节点按照满的计算
                res = countNodes(root.left)+(1<<right);
            }
            return res;
        }
        public int getDepth(TreeNode node){
            if(node==null){
                return 0;
            }
            return Math.max(getDepth(node.left),getDepth(node.right))+1;
        }
    }
    
  • 相关阅读:
    16-高级指针
    15-C语言结构体
    14-C语言宏
    13-C语言字符串函数库
    12-C语言字符串
    11-C语言指针
    10-C语言函数
    POJ 1001 高精度乘法
    POJ 1060 多项式乘法和除法取余
    POJ 1318 字典排序
  • 原文地址:https://www.cnblogs.com/itjiangpo/p/14181335.html
Copyright © 2011-2022 走看看