1.二叉树的层序遍历
LeetCode链接
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
queue<TreeNode*> vq;
if(root==NULL) return result;
TreeNode* cur = root;
vq.push(root);
while(!vq.empty()){
int len = vq.size();
vector<int> sresult;
for(int i=0; i<len; i++){
cur = vq.front();
vq.pop();
if(cur->left) vq.push(cur->left);
if(cur->right) vq.push(cur->right);
sresult.push_back(cur->val);
}
result.push_back(sresult);
}
return result;
}
2.翻转二叉树
LeetCode链接
- 前序/后续遍历法
- 中序遍历法不好用,因为在处理完左子树后,处理父节点将已经改变过的左节点和为改变过的右节点进行了交换
TreeNode* invertTree(TreeNode* root) {
if(!root) return root;
stack<TreeNode*> si;
si.push(root);
while(!si.empty()){
TreeNode* cur = si.top();
if(cur != NULL){
si.pop();
if(cur->right) si.push(cur->right);
if(cur->left) si.push(cur->left);
si.push(cur);
si.push(NULL);
}else{
si.pop();
cur = si.top();
swap(cur->left, cur->right);
si.pop();
}
}
return root;
}
- 递归法(三部曲)
- 确定参数和返回条件(参数就是没次遍历的节点点,返回参数为void)
- 确定终止条件:遍历到叶子节点(遇到空节点就停止)
- 单层逻辑:往下递归每个节点,翻转每个节点的左右子节点
class Solution {
public:
void invertNode(TreeNode* node){
if(!node) return;
invertNode(node->left);
invertNode(node->right);
TreeNode* temp = node->left;
node->left = node->right;
node->right = temp;
}
TreeNode* invertTree(TreeNode* root) {
invertNode(root);
return root;
}
};
TreeNode* invertTree(TreeNode* root) {
queue<TreeNode*> tq;
if(root != NULL) tq.push(root);
while(!tq.empty()){
int size = tq.size();
for(int i=0; i<size; i++){
TreeNode* node = tq.front();
swap(node->left, node->right);
tq.pop();
if(node->left) tq.push(node->left);
if(node->right) tq.push(node->right);
}
}
return root;
}
3.对称二叉树
LeetCode链接
class Solution {
public:
bool compareNode(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 = compareNode(left->left, right->right);
bool inside = compareNode(left->right, right->left);
return outside && inside;
}
bool isSymmetric(TreeNode* root) {
return compareNode(root->left, root->right);
}
};
bool isSymmetric(TreeNode* root) {
queue<TreeNode*> tq;
tq.push(root->left);
tq.push(root->right);
while(!tq.empty()){
TreeNode* left = tq.front();
tq.pop();
TreeNode* right = tq.front();
tq.pop();
if(left==NULL && right==NULL){
continue;
}
if(left==NULL && right!=NULL || left!=NULL&&right==NULL || left->val != right->val){
return false;
}
tq.push(left->left);
tq.push(right->right);
tq.push(left->right);
tq.push(right->left);
}
return true;
}