方便之後複習,記錄一下leetcode上有關於樹的幾道題
先是樹的前序遍歷、中序遍歷、和後序遍歷
分別是leetcode上144、94、145
前序遍歷就是先根結點 – 左子樹 – 右子樹
中序遍歷就是左子樹 – 根結點 – 右子樹
後序遍歷就是左子樹 – 右子樹 --根結點
代碼:遞歸方法
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//前序遍歷
class Solution {
public:
vector<int> res;
vector<int> preorderTraversal(TreeNode* root) {
order(root);
return res;
}
void order(TreeNode* root)
{
if (root == NULL)
{
return;
}
else
{
res.push_back(root->val); //前序遍歷 這裏放在前面 因爲根結點要先進來
order(root->left);
order(root->right);
}
}
};
//中序遍歷
class Solution {
public:
vector<int> res;
vector<int> inorderTraversal(TreeNode* root) {
order(root);
return res;
}
void order(TreeNode *root)
{
if (root == NULL)
{
return;
}
else
{
order(root->left);
res.push_back(root->val); //中序遍歷,這個放在這裏 這樣可以保證先左在根在右
order(root->right);
}
}
};
//後序遍歷
class Solution {
public:
vector<int> res;
vector<int> postorderTraversal(TreeNode* root) {
order(root);
return res;
}
void order(TreeNode* root)
{
if (root == NULL)
{
return;
}
else
{
order(root->left);
order(root->right);
res.push_back(root->val);
}
}
};
這個可以找個例子 按照代碼走一遍就明白了
然後是層序遍歷
層序遍歷主要是用bfs
但是bfs出來的結果沒有把樹的每一層分開
所以在再進一步做點處理
下邊先寫bfs在做一下處理
//BFS
class Solution_bfs {
public:
vector<int> bfs(TreeNode* root) {
vector<int> res;
queue<TreeNode*> que; //隊列
que.push(root);
while (1)
{
if (que.empty())
{
break;
}
auto node = que.front();
res.push_back(node->val);
que.pop();
if (node->left != NULL)
{
que.push(node->left);
}
if (node->right != NULL)
{
que.push(node->right);
}
}
return res;
}
};
//加一個for循環 使每一次 一個層裏面的都出來 而不是一個一個的出來
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
queue<TreeNode*> que;
que.push(root);
while (true)
{
vector<int> res;
if (que.empty())
{
break;
}
auto n = que.size();
//輸出這層結果,並且把下一層節點放進que裏面
for (int i = 0; i < n; i++)
{
auto node = que.front();
res.push_back(node->val);
que.pop();
if (node->left != NULL)
{
que.push(node->left);
}
if (node->right != NULL)
{
que.push(node->right);
}
}
ans.push_back(res);
}
}
};
leetcode 101:
/*
給定一個二叉樹,檢查它是否是鏡像對稱的。
例如,二叉樹 [1,2,2,3,4,4,3] 是對稱的。
*/
/*
解析,深度優先搜索 左樹的左節點和右樹的右節點相等,左樹的右節點和右樹的左節點相等
*/
#include<iostream>
#include<vector>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (root == NULL)
{
return true;
}
else
{
return ismoirror(root->left,root->right);
}
}
bool ismoirror(TreeNode *rootleft,TreeNode *rootright)
{
if (rootleft == NULL && rootright == NULL)
{
return true;
}
if ((rootleft == NULL && rootright != NULL) || (rootleft != NULL && rootright == NULL))
{
return false;
}
auto res = rootleft->val == rootright->val && ismoirror(rootleft->left, rootright->right) && ismoirror(rootleft->right,rootright->left);
return res;
}
};