解法一:遞迴
int countNodes(TreeNode* root) { if (root == NULL) return 0; TreeNode *pLeft = root->left; TreeNode *pRight = root->right; int ldepth = 0, rdepth = 0; while (pLeft) { ldepth++; pLeft = pLeft->left; } while (pRight) { rdepth++; pRight = pRight->right; } if (ldepth == rdepth) return (1 << (ldepth + 1)) - 1; else return countNodes(root->left) + countNodes(root->right) + 1; }
解法二:迭代
int GetDepth(TreeNode *root) { int depth = 0; while (root) { depth++; root = root->left; } return depth; } int countNodes(TreeNode* root) { if (root == NULL) return 0; int depth = GetDepth(root); int leaf = 0; int depth_left, depth_right; while (true) { depth_left = GetDepth(root->left); depth_right = GetDepth(root->right); if (depth_left == 0 && depth_right == 0) { leaf += 1; break; } if (depth_left == depth_right) { leaf += 1 << (depth_left - 1); root = root->right; } else { root = root->left; } } return (1 << (depth - 1)) - 1 + leaf; }