2022.2.15 leetcode刷题——树
/**
* 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:
TreeNode* mirrorTree(TreeNode* root) {
if(root==NULL)
{
return root;
}
TreeNode* temp = root->left;
root->left=root->right;
root->right=temp;
mirrorTree(root->left);
mirrorTree(root->right);
return root;
}
};
后序递归:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==NULL)
{
return 0;
}
int res1 = maxDepth(root->left);
int res2 = maxDepth(root->right);
return max(res1,res2)+1;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int depth = 0;
int minDepth(TreeNode* root) {
if(root==nullptr)
{
return 0;
}
if(root->left==nullptr && root->right==nullptr )
{
depth= 1;
}
if(root->left==nullptr && root->right!=nullptr )
{
depth = 1+minDepth(root->right);
}
if(root->left!=nullptr && root->right==nullptr )
{
depth = 1+minDepth(root->left);
}
if(root->left!=nullptr && root->right!=nullptr )
{
depth = 1+min(minDepth(root->right),minDepth(root->left));
}
return depth;
}
};
二叉树的层序遍历:
/**
* 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:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
if(root==NULL)
{
return result;
}
vector<int> temp_result;
queue<TreeNode*> myque;
myque.push(root);
while(!myque.empty())
{
int size=myque.size();
for(int i=0;i<size;i++)
{
TreeNode* temp = myque.front();
myque.pop();
temp_result.push_back(temp->val);
if(temp->left)
{
myque.push(temp->left);
}
if(temp->right)
{
myque.push(temp->right);
}
}
result.push_back(temp_result);
temp_result.clear();
}
return result;
}
};