Leetcode 222. Count Complete Tree Nodes | | Leetcode 222. Count Complete Tree Nodes 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 1. Description 2. Solution1234567891011121314151617181920212223242526272829303132333435/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int countNodes(TreeNode* root) { if(!root) { return 0; } int leftDepth = 0; int rightDepth = 0; TreeNode* left = root; TreeNode* right = root; while(left) { leftDepth++; left = left->left; } while(right) { rightDepth++; right = right->right; } if(leftDepth == rightDepth) { return pow(2, leftDepth) - 1; } else { return 1 + countNodes(root->left) + countNodes(root->right); } }}; Reference https://leetcode.com/problems/count-complete-tree-nodes/description/ 如果有收获,可以请我喝杯咖啡! 赏 微信打赏 支付宝打赏