102. 二叉树的层序遍历
https://leetcode.cn/problems/binary-tree-level-order-traversal/
解题方法:
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> que;
if(root != NULL) que.push(root);
vector<vector<int>>result;
while(!que.empty())
{
int size = que.size();
vector<int> vec;
for(int i = 0; i < size; i++)
{
TreeNode * node = que.front();
que.pop();
vec.push_back(node->val);
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
result.push_back(vec);
}
return result;
}
};
226.翻转二叉树
题目链接:
https://leetcode.cn/problems/invert-binary-tree/
解题方法:
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL) return root;
swap(root->left,root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
101. 对称二叉树
题目链接:
https://leetcode.cn/problems/symmetric-tree/
解题方法:
class Solution {
public:
bool compare(TreeNode* left,TreeNode* right)
{
if(left == NULL && right != NULL) return false;
else if(left != NULL && right == NULL) return false;
else if(left == NULL && right == NULL) return true;
else if(left ->val != right ->val ) return false;
bool outside = compare(left->left, right->right);
bool inside = compare(left->right, right->left);
bool isSame = outside && inside;
return isSame;
}
bool isSymmetric(TreeNode* root) {
if(root == NULL) return true;
return compare(root->left,root->right);
}
};