一、二叉树的前序遍历LeetCode144题
题目描述及解析可参考博客 https://blog.csdn.net/chenxiyuehh/article/details/86931798
基本思路均相同,只是实现语言不同,C++比C语言实现要简单的多,毕竟可以直接使用vector和stack,不用像C语言一样还得自己实现一个栈,也可以将遍历序列直接存入vector中,而不用像C语言一样要遍历两遍二叉树,第一遍为确定为遍历序列开辟多大空间的数组,第二遍才是将遍历序列存入数组中。
代码实现
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> preV;
if(root == NULL)
return preV;
stack<TreeNode*> st;
TreeNode* cur = root;
while (st.empty() != 1 || cur != NULL)
{
// 1.访问坐路节点并入栈
while (cur != NULL)
{
preV.push_back(cur->val);
st.push(cur);
cur = cur->left;
}
struct TreeNode* top = st.top();
st.pop();
// 子问题:访问右子树
cur = top->right;
}
return preV;
}
};
二、二叉树的中序遍历Leetcode94题
代码实现
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> inV;
if(root == NULL)
return inV;
TreeNode* cur = root;
stack<TreeNode*> st;
while(st.empty() != 1 || cur != NULL)
{
while(cur != NULL)
{
st.push(cur);
cur = cur->left;
}
TreeNode* top = st.top();
inV.push_back(top->val);
st.pop();
//子问题,访问左路结点的右子树
cur = top->right;
}
return inV;
}
};
三、二叉树的后序遍历LeetCode145题
代码实现
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> postV;
if(root == NULL)
return postV;
TreeNode* cur = root;
TreeNode* prev = NULL;//定义一个指针指向cur的前一个位置
stack<TreeNode*> st;
while(st.empty() != 1 || cur != NULL)
{
//访问左路结点并入栈
while(cur != NULL)
{
st.push(cur);
cur = cur->left;
}
TreeNode* top = st.top();
if(top->right == NULL || top->right == prev)
{
postV.push_back(top->val);
st.pop();
prev = top;
}
else
{
//子问题,访问左路结点的右子树
cur = top->right;
}
}
return postV;
}
};