/**
* 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) {
if(root == null) {
return 0;
}
TreeNode left = root.left;
TreeNode right = root.right;
int leftDepth = 0;
int rightDepth = 0;
while(left!=null){
left=left.left;
leftDepth++;
}
while(right!=null){
right=right.right;
rightDepth++;
}
if(leftDepth==rightDepth){
return (2<<leftDepth)-1;
}
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
代码随想录——222. 完全二叉树的节点个数
最新推荐文章于 2024-06-30 14:35:18 发布