/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
int left = leftHeight(root);
int right = rightHeight(root);
if (left == right) {
return (2<<left) - 1;
} else {
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
private int leftHeight(TreeNode node) {
TreeNode left = node.left;
int height = 0;
while (left != null) {
left = left.left;
height++;
}
return height;
}
private int rightHeight(TreeNode node) {
TreeNode right = node.right;
int height = 0;
while (right != null) {
right = right.right;
height++;
}
return height;
}
}
Count Complete Tree Nodes
最新推荐文章于 2023-09-23 20:10:58 发布