LeetCode104
题目:
解法:
class Solution {
public:
void order(TreeNode* cur,int &deep,int depth)
{
if(cur == nullptr) return;
if(deep == depth) deep++;
order(cur->left,deep,depth+1);
order(cur->right,deep,depth+1);
}
int maxDepth(TreeNode* root) {
int deep = 0;
int depth = 0;
order(root,deep,depth);
return deep;
}
};
Leetcode 559
题目:
解法:
class Solution {
public:
void find_deepest(int &deep,int depth,Node* node){
if(node == nullptr) return ;
int size = node -> children.size();
if(deep == depth) deep ++;
for(int i = 0; i < size; i++){
find_deepest(deep , depth + 1 ,node -> children[i]);
}
}
int maxDepth(Node* root) {
int depth = 0;
int deep = 0;
find_deepest(deep, depth, root);
return deep;
}
};
LeetCode 111
题目:
解法1:(层序遍历)
class Solution {
public:
int minDepth(TreeNode* root) {
queue<TreeNode*> que;
int deep;
if(root != NULL) que.push(root);
deep = 0;
while(!que.empty()){
int size = que.size();
int bb = 0;
for(int i = 0;i < size;i++)
{
TreeNode* node = que.front();
if(node->left == nullptr && node->right == nullptr)
{
deep = deep + 1;
bb = 1;
break;
}
que.pop();
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
if(bb == 1)
{
break;
}
deep++;
}
return deep;
}
};
解法2:(自己想的递归)
class Solution {
public:
void find_min(TreeNode* node, int depth,int &deep){
if(node == nullptr){
return;
}
if(node ->left == nullptr && node ->right == nullptr && deep == 0){
deep = depth;
}
else if(node ->left == nullptr && node ->right == nullptr && deep != 0){
deep = deep > depth ? depth : deep;
}
find_min(node -> left,depth+1,deep);
find_min(node -> right,depth+1,deep);
}
int minDepth(TreeNode* root) {
int deep = 0;
int depth = 1;
find_min(root,depth,deep);
return deep;
}
};
解法3:(官方递归)
class Solution {
public:
int find_min(TreeNode* node){
if(node == nullptr){
return 0;
}
int leftdeep,rightdeep,deep;
if(node -> left == NULL && node -> right != NULL){
deep = 1 + find_min(node -> right);
}
else if(node -> left != NULL && node -> right == NULL){
deep = 1 + find_min(node -> left);
}
else deep = 1 + min(find_min(node -> left),find_min(node -> right));
return deep;
}
int minDepth(TreeNode* root) {
int deep = find_min(root);
return deep;
}
};
LeetCode222:
解法:
class Solution {
public:
int countNodes(TreeNode* root) {
if(root == NULL) return 0;
return countNodes(root -> right) + countNodes(root -> left) + 1;
}
};