二叉树的统一迭代法遍历

中序遍历

中序遍历无法直接利用栈进行遍历,需要利用指针进行遍历,对栈中的节点进行操作。
对于中间节点,如果指针遍历到了,但没有进行处理,就再push()一个nullptr,作为标记,说明这个节点只是遍历过了,但是没有处理。事实上,每个待处理(放入vector)中的节点,其在栈中的上层元素都会是nullptr

#include <iostream>
#include <stack>
#include <vector>
using std::stack;
using std::vector;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

class Solution {
  public:
    vector<int> inorderTraversal(TreeNode *root) {
        vector<int> result;
        stack<TreeNode *> st;
        if (root != nullptr)
            st.push(root);
        while (!st.empty()) {
            TreeNode *node = st.top();
			//对节点进行遍历
            if (node != nullptr) {
                st.pop(); // 将该节点弹出,避免重复操作,下面再将右中左节点添加到栈中
                if (node->right != nullptr)
                    st.push(node->right);
                st.push(node);
                st.push(nullptr);
                if (node->left != nullptr)
                    st.push(node->left);
            } else {//依次处理节点
                st.pop();
                node = st.top();
                st.pop();
                result.push_back(node->val);
            }
        }
        return result;
    }
};

前序遍历

相比中序遍历,只是需要调整遍历部分,即st.push()的顺序即可。

vector<int> preorderTraversal(TreeNode *root) {
    vector<int> result;
    stack<TreeNode *> st;
    if (root != nullptr)
        st.push(root);
    while (!st.empty()) {
        TreeNode *node = st.top();
        if (node != nullptr) {
            st.pop();
            if (node->right != nullptr)
                st.push(node->right);
            if (node->left != nullptr)
                ;
            st.push(node->left);
            st.push(node);
            st.push(nullptr);
        } else {
            st.pop();
            node = st.top();
            st.pop();
            result.push_back(node->val);
        }
    }
}

后序遍历

相比中序遍历也只是调整遍历顺序而已

vector<int> postorderTraversal(TreeNode *root) {
    vector<int> result;
    stack<TreeNode *> st;
    if (root != nullptr)
        st.push(root);
    while (!st.empty()) {
        TreeNode *node = st.top();
        if (node != nullptr) {
            st.pop();
            st.push(node);
            st.push(nullptr);
            if (node->right != nullptr)
                st.push(node->right);
            if (node->left != nullptr)
                st.push(node->left);
        } else {
            st.pop();
            node = st.top();
            st.pop();
            result.push_back(node->val);
        }
    }
}

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...