102二叉树的层序遍历
二叉树的宽度深度都可以用层序遍历
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>>result;
if(!root) return result;
queue<TreeNode*>q;
q.push(root);
while(!q.empty()){
int size = q.size();
vector<int>path;
while(size--){
TreeNode* temp = q.front();
path.push_back(temp->val);
q.pop();
if(temp->left) q.push(temp->left);
if(temp->right) q.push(temp->right);
}
result.push_back(path);
}
return result;
}
};
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
最小深度
- 既没有左节点,又没有右节点 返回0
- 只有一个节点, 返回存在的子节点的深度
- 左右节点都有,返回小的那个
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
if(!root->left || !root->right)
return minDepth(root->left) + minDepth(root->right) + 1;
return min(minDepth(root->right), minDepth(root->left)) + 1;
}
};
从当前root节点看问题
我的新左节点应该是把右子节点翻转后的返回节点
我的新右节点应该是把左子节点翻转后的返回节点
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root) return root;
TreeNode * left = invertTree(root->right);
TreeNode * right = invertTree(root->left);
root->left = left;
root->right = right;
return root;
}
};
直接使用swap进行值的更改
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root) return root;
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
101. 对称二叉树
本题比较的是左右子树,要另开一个函数
class Solution {
public:
bool isSymmetric(TreeNode* root) {
return judge(root->left, root->right);
}
bool judge(TreeNode* left, TreeNode* right){
if(!left && !right) return true;
if(!left || !right) return false;
if(left->val != right->val) return false;
return judge(left->left, right->right) && judge(left->right, right->left);
}
};