层序遍历
题目
给你二叉树的根节点 root
,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
示例
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*>que;
vector<vector<int>> ret;
if (root != NULL)
{
que.push(root);
}
while(!que.empty())
{
vector<int>vec;
int size = que.size();
while(size--)
{
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);
}
}
ret.push_back(vec);
}
return ret;
}
};
226.翻转二叉树
题目
给你一棵二叉树的根节点 root
,翻转这棵二叉树,并返回其根节点。
示例
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == NULL)
{
return root;
}
swap(root->left, root->right);
if (root->left)
{
invertTree(root->left);
}
if (root->right)
{
invertTree(root->right);
}
return root;
}
};
101. 对称二叉树
题目
给你一个二叉树的根节点 root
, 检查它是否轴对称。
示例
class Solution {
public:
bool compare(TreeNode* left, TreeNode* right)
{
if (left == NULL && right == NULL)
{
return true;
}
else if (left == NULL && right != NULL)
{
return false;
}
else if (left != NULL && right == NULL)
{
return false;
}
else if (left->val != right->val )
{
return false;
}
bool outside = compare(left->left, right->right);
bool inside = compare(left->right, right->left);
bool result = outside && inside;
return result;
}
bool isSymmetric(TreeNode* root) {
if (root == NULL)
{
return true;
}
bool result = compare(root->left, root->right);
return result;
}
};