102. 二叉树的层序遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
if(root == NULL) return ans;
queue<TreeNode*> que;
TreeNode* cur = root;
que.push(cur);
while(!que.empty()){
vector<int> subans;
int size = que.size();
for(int i=0; i<size; i++){
cur = que.front();
que.pop();
subans.push_back(cur->val);
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
}
ans.push_back(subans);
}
return ans;
}
};
226. 翻转二叉树
1.递归法
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
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;
}
};
2.迭代法
和前序遍历类似,处理中节点的时候交换左右孩子
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL) return root;
stack<TreeNode*> st;
TreeNode* cur = root;
st.push(cur);
while(!st.empty()){
cur = st.top();
st.pop();
swap(cur->left, cur->right);
if(cur->right) st.push(cur->right);
if(cur->left) st.push(cur->left);
}
return root;
}
};
101. 对称二叉树
递归法
比较左右节点,需要两个参数。
终止条件:
先判断含空节点的情况
1 左空-右不空 返回false
2 左不空-右空 返回false
3 左右都为空 返回true
再判断非空但值不同 返回false
还剩下都不为空并且值相等,继续递归,分内侧外侧比较
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
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 out = compare(left->left, right->right);
bool in = compare(left->right, right->left);
return out && in;
}
bool isSymmetric(TreeNode* root) {
return compare(root->left, root->right);
}
};