2021.11.09 - SX07-11.完全二叉树的节点个数

1. 题目

在这里插入图片描述
在这里插入图片描述

2. 思路

(1) 递归

  • 首先计算左右子树的高度,由于二叉树是完全二叉树,假设二叉树的高度为k,则可能出现两种情况:
    1. 左子树的高度为k-1,右子树的高度为k-1,此时,左子树是高度为k-1的满二叉树,因此,左子树的结点数可以直接解得2^(k-1)-1,右子树的结点数通过递归得到,再加上根结点的1即可。
    2. 左子树的高度为k-1,右子树的高度为k-2,此时,右子树的高度为k-2的满二叉树,因此,右子树的结点数可以直接解得2^(k-2)-1,左子树的结点数通过递归得到,再加上根结点的1即可。

3. 代码

public class Test {
    
    
    public static void main(String[] args) {
    
    
    }
}

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) {
    
    
        if (root == null) {
    
    
            return 0;
        }
        int leftDepth = getDepth(root.left);
        int rightDepth = getDepth(root.right);
        if (leftDepth == rightDepth) {
    
    
            return (int) Math.pow(2, leftDepth) - 1 + countNodes(root.right) + 1;
        } else {
    
    
            return countNodes(root.left) + (int) Math.pow(2, rightDepth) - 1 + 1;
        }
    }

    private int getDepth(TreeNode root) {
    
    
        if (root == null) {
    
    
            return 0;
        }
        return Math.max(getDepth(root.left), getDepth(root.right)) + 1;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44021223/article/details/121233921