102. 二叉树的层序遍历
给你二叉树的根节点 root
,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:[[3],[9,20],[15,7]]
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
deque<TreeNode*> que;
if(!root) return result;
que.push_front(root);
while(!que.empty()){
int size = que.size();
vector<int> res;
while(size--){
auto cur = que.front();
que.pop_front();
res.push_back(cur->val);
if(cur->left) que.push_back(cur->left);
if(cur->right) que.push_back(cur->right);
}
result.push_back(res);
}
return result;
}
};
思路:二维数组保存数据,一维是每一层的节点。将每一层节点的左右节点都放入队列中,并计算队列的长度,将队列弹出得到下一层的节点。
226. 翻转二叉树
给你一棵二叉树的根节点 root
,翻转这棵二叉树,并返回其根节点。
示例 1:
输入:root = [4,2,7,1,3,6,9] 输出:[4,7,2,9,6,3,1]
递归中左右或者左右中进行翻转,如果是左中右递归时的参数是同一侧节点。
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root) return NULL;
swap(root->left,root->right);
if(root->left) invertTree(root->left);
if(root->right) invertTree(root->right);
return root;
}
};
迭代 中左右:中右左
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root) return NULL;
stack<TreeNode*> st;
st.push(root);
auto cur = root;
while(!st.empty()){
auto 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. 对称二叉树
给你一个二叉树的根节点 root
, 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3] 输出:true
class Solution {
public:
bool compare(TreeNode* l, TreeNode* r){
if(!l && !r) return true;
else if(!l || !r || l->val!= r->val) return false;
return compare(l->left,r->right) && compare(l->right,r->left);
}
bool isSymmetric(TreeNode* root) {
if(!root) return true;
return compare(root->left,root->right);
}
};
注意递归的参数和返回值