一 102 二叉树的层序遍历
层序遍历是队列的典型应用,是图的广度优先遍历的简化版
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> que;
if(root != nullptr)
que.push(root);
vector<vector<int>> result;
while(!que.empty()){
vector<int> tmp;
int size = que.size();
for(int i = 0; i < size; i++){
TreeNode* Node = que.front();
que.pop();
tmp.push_back(Node->val);
if(Node->left != nullptr)
que.push(Node->left);
if(Node->right != nullptr)
que.push(Node->right);
}
result.push_back(tmp);
}
return result;
}
};
二 226 反转二叉树
前序遍历和后序遍历都可以,中序遍历要稍微注意一下,遍历顺序为左中左,否则某些节点的左右孩子会翻转两次。
//递归 中序遍历
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == nullptr)
return nullptr;
invertTree(root->left);
swap(root->left,root->right);
invertTree(root->left);
return root;
}
};
//迭代 前序遍历
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == NULL) return root;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()) {
TreeNode* node = st.top(); // 中
st.pop();
swap(node->left, node->right);
if(node->right) st.push(node->right); // 右
if(node->left) st.push(node->left); // 左
}
return root;
}
};
三 101对称二叉树
class Solution {
public:
bool compare(TreeNode* left, TreeNode* right) {
//这里的left 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); // 左子树:右、 右子树:左
return outside && inside;;
}
bool isSymmetric(TreeNode* root) {
if (root == NULL) return true;
return compare(root->left, root->right);
}
};
四 总结
- 反转二叉树和对称二叉树都要注意递归过程的实现,每一层的逻辑。