之前用层序遍历迭代法写过;
递归法:
class Solution {
public:
int getDepth(TreeNode* root){
if(root==NULL) return 0;
int leftdeep = getDepth(root->left);
int rightdeep = getDepth(root->right);
int depth = max(leftdeep,rightdeep) + 1;
return depth;
}
int maxDepth(TreeNode* root) {
return getDepth(root);
}
};
递归法主要有三个步骤,第一步确定输入的参数,第二部确定递归终止条件,第三步确定单次递归内逻辑;用后序遍历代码好写;
递归法:
class Solution {
public:
int getDepth(TreeNode* node){
if(node==NULL) return 0;
int leftdeep = getDepth(node->left);
int rightdeep = getDepth(node->right);
if(node->left==NULL&&node->right){
return 1 + rightdeep;
}
if(node->right==NULL&&node->left){
return 1 + leftdeep;
}
int result = 1 + min(rightdeep,leftdeep);
return result;
}
int minDepth(TreeNode* root) {
return getDepth(root);
}
};
普通二叉树:
递归:
class Solution {
public:
int getNode(TreeNode* node){
if(node==NULL) return 0;
int leftNum = getNode(node->left);
int rightNum = getNode(node->right);
int num = leftNum + rightNum + 1;
return num;
}
int countNodes(TreeNode* root) {
return getNode(root);
}
};
迭代:
class Solution {
public:
int countNodes(TreeNode* root) {
queue<TreeNode*> que;
int num = 0;
if(root!=NULL) que.push(root);
while(!que.empty()){
int size = que.size();
for(int i = 0;i<size;i++){
TreeNode* cur = que.front();
que.pop();
num++;
if(cur->left!=NULL) que.push(cur->left);
if(cur->right!=NULL) que.push(cur->right);
}
}
return num;
}
};