1二叉树构建
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) {}
};
2 二叉树的遍历方式
二叉树最重要的四种遍历方式:前序遍历、中序遍历、后序遍历、层序遍历。
其中层序遍历最好理解,就是将二叉树从根节点向下,一层一层遍历出来,遍历出来的结果就是一个二维数组,一维长度就是数的高度,二维长度就是每层的节点的个数。
其次就是前中后序遍历:
前序遍历:根结点-左结点-右结点
中序遍历:左结点-根节点-右结点
后序遍历:左节点-右结点-根结点
(有一个很好记的方法,就是记根节点的位置,在前就是前序,在中就是中序,在后就是后续,因为左右的相对顺序是不会变的)
下面我们来看下二叉树遍历方式的具体实现:
前序遍历
递归版本
class Solution {
public:
vector<int> ans;
vector<int> preorderTraversal(TreeNode* root) {
if (!root) return ans;
dfs(root);
return ans;
}
void dfs(TreeNode* root)
{
if (!root) return;
ans.push_back(root->val);//根
dfs(root->left);//左
dfs(root->right);//右
}
};
迭代版本
class Solution {
public:
vector<int> ans;
stack<TreeNode*> mystack;
vector<int> preorderTraversal(TreeNode* root) {
while (root || !mystack.empty())
{
while (root)
{
ans.push_back(root->val);//根
mystack.push(root);
root = root->left;//左
}
root = mystack.top();
mystack.pop();
root = root->right;//右
}
return ans;
}
};
中序遍历
递归版本
class Solution {
public:
vector<int> ans;
vector<int> inorderTraversal(TreeNode* root) {
dfs(root);
return ans;
}
void dfs(TreeNode* root)
{
if (!root) return;
dfs(root->left);//左
ans.push_back(root->val);//根
dfs(root->right);//右
}
};
迭代版本
class Solution {
public:
vector<int> ans;
vector<int> inorderTraversal(TreeNode* root) {
if (!root) return ans;
stack<TreeNode*> mystk;
while (root || !mystk.empty())
{
while (root)
{
mystk.push(root);
root = root->left;//左
}
root = mystk.top();
ans.push_back(root->val);//根
mystk.pop();
root = root->right;//右
}
return ans;
}
};
后序遍历
递归版本
class Solution {
public:
vector<int> ans;
vector<int> postorderTraversal(TreeNode* root) {
dfs(root);
return ans;
}
void dfs(TreeNode* root)
{
if (!root) return;
dfs(root->left);//左
dfs(root->right);//右
ans.push_back(root->val);//根
}
};
迭代版本
迭代版本,最为复杂的一个,需要先根据前序遍历的思路得到根结点->右结点->左结点
//然后将得到的结果翻转即可得到正确的结果左->右->根
class Solution {
public:
vector<int> ans;
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> mystack;
TreeNode* cur = root;
while (cur || !mystack.empty())
{
while (cur)
{
ans.push_back(cur->val);//根
mystack.push(cur);
cur = cur->right;//右
}
cur = mystack.top();
mystack.pop();
cur = cur->left;//左
}
reverse(ans.begin(), ans.end());//翻转后:左右根
return ans;
}
};
层序遍历
class Solution {
public:
vector<vector<int>> ans;
vector<vector<int>> levelOrder(TreeNode* root) {
if (!root) return ans;
queue<TreeNode*> que;
que.push(root);
while (!que.empty())
{
vector<int> path;//记录每一层的结点的值
int n = que.size();//每一层的结点数
while (n--)
{
root = que.front();
path.push_back(root->val);
que.pop();
if (root->left) que.push(root->left);
if (root->right) que.push(root->right);
}
ans.push_back(path);
}
return ans;
}
};
PS:前中后序的递归版本代码非常的简单,所以如果有能力的情况下,最好还是学会迭代版本,其原理是利用了栈结构的先入后出的原则,实现了前中后序遍历,而层序遍历则利用了队列的先入先出原则实现,这个需要特别的注意一下,上面的代码可以直接当做模板。