102. 二叉树的层序遍历
题目链接/文章讲解/视频讲解:链接地址
代码思路:利用递归法去逐层遍历出二叉树的节点,BFS.
/**
* 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:
void Current(TreeNode* cur, vector<vector<int>>& result, int depth) { // 注意vector 传的是二维数组
if (cur == nullptr) return;
if (depth == result.size()) result.push_back(vector<int>());
result[depth].push_back(cur->val);
Current(cur->left, result, depth + 1);
Current(cur->right, result, depth + 1);
}
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
int depth = 0; // 记录层
Current(root,result,depth);
return result;
}
};
二叉树的层序遍历还有9题类似的,以后有时间再补上。
226.翻转二叉树
题目链接/文章讲解/视频讲解:链接地址
代码思路:利用递归找到节点的左右子节点进行交换。
/**
* 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:
void Current(TreeNode* cur) {
if (cur == nullptr) return;
swap(cur->left, cur->right);
Current(cur->left);
Current(cur->right);
}
TreeNode* invertTree(TreeNode* root) {
Current(root);
return root;
}
};
101. 对称二叉树
题目链接/文章讲解/视频讲解:链接地址
代码思路:将二叉树分成左右两个子树,然后利用递归法,找到二叉树两个子树对应应该相等的节点的值进行对比。
/**
* 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 Current(TreeNode* cur1, TreeNode* cur2) {
if (cur1 == nullptr && cur2 != nullptr) return false;
else if (cur1 != nullptr && cur2 == nullptr) return false;
else if (cur1 == nullptr && cur2 == nullptr) return true;
else if (cur1->val != cur2->val) return false;// 要先排除空节点才能判断,不然会出错。要比较的是val
//递归比较值
bool outSide = Current(cur1->left, cur2->right);
bool inSide = Current(cur1->right, cur2->left);
return outSide && inSide;
}
bool isSymmetric(TreeNode* root) {
if (root == nullptr) return true;
TreeNode* leftNode = root->left;
TreeNode* rightNode = root->right;
return Current(leftNode, rightNode);
}
};