classSolution{public:intmaxDepth(TreeNode* root){if(nullptr== root)return0;int left =maxDepth(root->left);// 计算左子树的高度int right =maxDepth(root->right);// 计算右子树的高度returnmax(left, right)+1;}};
classSolution{public:inttraversal(TreeNode *cur){if(nullptr== cur)return0;int left =traversal(cur->left);int right =traversal(cur->right);if(cur->left ==nullptr&& cur->right !=nullptr)return right +1;if(cur->left !=nullptr&& cur->right ==nullptr)return left +1;return1+min(left, right);}intminDepth(TreeNode* root){returntraversal(root);}};
classSolution{public:inttraversal(TreeNode *cur){if(nullptr== cur)return0;int left =traversal(cur->left);int right =traversal(cur->right);int sum =1+ left + right;// 此处的 1 是根节点return sum;}intcountNodes(TreeNode* root){returntraversal(root);}};
层序遍历
classSolution{public:intcountNodes(TreeNode* root){if(nullptr== root)return0;
queue<TreeNode *> que;
que.push(root);int sum =0;while(!que.empty()){int size = que.size();
sum += size;for(int i =0; i < size; i++){
TreeNode *cur = que.front();
que.pop();if(cur->left) que.push(cur->left);if(cur->right)que.push(cur->right);}}return sum;}};