美文网首页
222. 完全二叉树的节点个数

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

作者: Abeants | 来源:发表于2021-10-15 20:12 被阅读0次

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

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

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

解题思路及方法

如果用简单得递归,很快就能写出来,如下:

class Solution {
    public int nums = 0;

    public void count1(TreeNode root) {
        if (root == null) return;;
        nums++;
        count1(root.left);
        count1(root.right);
    }

    public int countNodes(TreeNode root) {
        count1(root);

        return this.nums;
    }
}

但是呢题目既然说了是完全二叉树,那么就要用到完全二叉树得性质。这篇博客写的很好,我就是按照他的思路来的。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int countNodes(TreeNode root) {
        TreeNode left = root, right = root;
        // 记录左右子树高度
        int leftHeight = 0, rightHeight = 0;
        while (left != null) {
            left = left.left;
            leftHeight++;
        }
        while (right != null) {
            right = right.right;
            rightHeight++;
        }
        if (leftHeight == rightHeight) {
            return (int) Math.pow(2, leftHeight) -1;
        }

        return 1 + countNodes(root.left) + countNodes(root.right);
    }
}

结果如下:

相关文章

网友评论

      本文标题:222. 完全二叉树的节点个数

      本文链接:https://www.haomeiwen.com/subject/tlrpoltx.html