代码随想录算法训练营第十五天 | 102.二叉树的层序遍历 226.翻转二叉树 101.对称二叉树
102.二叉树的层序遍历
思路:栈对应深度优先遍历,而广度优先遍历使用的是队列
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
queue<TreeNode*> que;
if(root == nullptr) return {};
TreeNode* node;
que.push(root);
while(!que.empty()) {
vector<int> temp;
// 在堆que进行出队入队操作之前一定要先保存当前队的大小(因为要将每层的节点分别保存)
int size = que.size();
while(size--) {
node = que.front();
que.pop();
if(node) {
temp.push_back(node->val);
que.push(node->left);
que.push(node->right);
}
}
if(!temp.empty())
ans.push_back(temp);
}
return ans;
}
};
N叉树的层序遍历
思路:和二叉树的层序遍历一样,只不过入队的时候加入当前节点的所有孩子
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
vector<vector<int>> ans;
queue<Node*> que;
if(root == nullptr) return {};
que.push(root);
while(!que.empty()) {
int size = que.size();
vector<int> temp;
for(int i = 0; i < size; ++i) {
Node* node = que.front();
que.pop();
temp.push_back(node->val);
for(auto it = node->children.begin(); it != node->children.end(); ++it) {
que.push(*it);
}
}
ans.push_back(temp);
}
return ans;
}
};
226.翻转二叉树
迭代法
思路:只需要遍历所有节点,并将遍历的节点的左孩子和右孩子交换即可
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
stack<TreeNode*> st;
if(root == nullptr) return root;
st.push(root);
while(!st.empty()) {
TreeNode* cur = st.top();
st.pop();
TreeNode* temp = cur->left;
cur->left = cur->right;
cur->right = temp;
if(cur->left) st.push(cur->left);
if(cur->right) st.push(cur->right);
}
return root;
}
};
101 对称二叉树
思路:递归的比较当前节点的左子树和右子树是否相等
递归法
class Solution {
public:
bool compare(TreeNode* lhs, TreeNode* rhs) {
if(lhs == nullptr && rhs == nullptr) return true;
else if(lhs == nullptr && rhs != nullptr) return false;
else if(lhs != nullptr && rhs == nullptr) return false;
else if(lhs->val != rhs->val) return false;
else {
return compare(lhs->left, rhs->right) && compare(lhs->right, rhs->left);
}
}
bool isSymmetric(TreeNode* root) {
if(root == nullptr) return true;
else return compare(root->left, root->right);
}
};