leetcode:力扣本题链接
leetcode所有深度遍历链接
!!!后文有动画演示一定要结合动画理解!!!
遍历顺序取决于中间节点所在的位置,假如中间节点在最后,那么就是后序遍历。
- 在非递归算法中,后序遍历和先序遍历是一对,先写出先序遍历的代码,然后调整左右节点入栈的顺序,最后把队列反序一下就得到了后序遍历。
- 中序遍历例外,需要添加一个指针,一直访问到树的最底层的左节点,压入栈,后续所有的左节点其实都等同于中间节点。
先序遍历(中左右)
递归
void preOrderRecur(TreeNode* root) {
if (root==nullptr)
return;
cout<<root->val<<",";
postOrderRecur(root->left);
postOrderRecur(root->right);
}
非递归
void preOrderRecur(TreeNode* root ) {
stack<TreeNode*> st;
vector<int> vec;
if (root == nullptr)
return;
st.push(root);
while (!st.empty())
{
TreeNode* node = st.top();
st.pop();
vec.push_back(node->val);
//cout << node->val << ", ";//打印
if (node->right) st.push(node->right);//进栈是右左,出栈才是左右
if (node->left) st.push(node->left);
}
for (int i = 0; i < vec.size(); i++) {
cout << vec[i] << ",";
}
}
后序遍历(左右中)
递归
void postOrderRecur(TreeNode* root) {
if (root==nullptr)
return;
postOrderRecur(root->left);
postOrderRecur(root->right);
cout<<root->val<<",";
}
非递归-利用一个堆栈
- 先序遍历中左右—>调整入栈顺序—>反序列数组,即可得到后序遍历。
void postOrderRecur(TreeNode* root ) { // 在先序遍历基础上改进
stack<TreeNode*> st;
vector<int> vec;
if (root == nullptr)
return;
st.push(root);
while (!st.empty())
{
TreeNode* node = st.top();
st.pop();
vec.push_back(node->val);
//cout << node->val << ", ";
if (node->left) st.push(node->left); //因为进栈和出栈顺序反了
if (node->right) st.push(node->right);
}
reverse(vec.begin(), vec.end());
for (int i = 0; i < vec.size(); i++) {
cout << vec[i] << ",";
}
}
中序遍历(左中右)
递归
void inOrderRecur(TreeNode* root) {
if (root==nullptr)
return;
postOrderRecur(root->left);
cout<<root->val<<",";
postOrderRecur(root->right);
}
非递归
void inOrderRecur(TreeNode* root ) { //添加一个指针,一直访问到最底层的左边节点
vector<int> vec;
stack<TreeNode*> st;
TreeNode* cur = root;
while (cur!=NULL||!st.empty()) {
if (cur) {
st.push(cur);
cur = cur->left;
}
else {
TreeNode* tmp = st.top();
vec.push_back(tmp->val);
st.pop();
if (tmp->right)cur = tmp->right;
}
}
for (int i = 0; i < vec.size(); i++) {
cout << vec[i] << ",";
}
}