Loading

LeetCode 222. 完全二叉树的节点个数

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

说明:

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

示例:

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

输出: 6

思路:分为两种情况,第一种是左子树的高度 n 与右子树的高度 m 相同,说明左子树已经填满了,左子树的节点数加上根节点的总数为 2^n,只需遍历右子树的节点个数即可;第二种是 n 与 m 不相等,说明右子树已经填满了,右子树的节点数加上根节点的总数为 2^m,只需遍历左子树的节点个数即可。这里计算节点个数要用到递归的思想。

/**
 * 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 n = countLevel(root.left);
        int m = countLevel(root.right);
        
        if(n == m){
            return (countNodes(root.right) + (1<<n));
        }
        else{
            return (countNodes(root.left) + (1<<m));
        }
    }
    private int countLevel(TreeNode root){
        if(root == null){
            return 0;
        }
        return Math.max(countLevel(root.left), countLevel(root.right)) + 1;
    }

}

在这里插入图片描述

posted @ 2020-11-24 23:13  XiaoJ_c  阅读(7)  评论(0)    收藏  举报