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