【leetcode 94. 二叉树的中序遍历】解题报告

前往二叉树的:前序,中序,后序 遍历算法

方法一:递归

    vector<int> res;
    vector<int> inorderTraversal(TreeNode* root) {
        if (!root) return res;
        if (root->left) inorderTraversal(root->left);      
        res.push_back(root->val);
        if (root->right) inorderTraversal(root->right);
        return res;
    }

方法二:非递归

    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        if (!root) return res;
        stack<TreeNode*> S;
        TreeNode* p = root;
        while(p||!S.empty())
        {
            if (p)
            {
                S.push(p);
                p=p->left;
            }
            else
            {
                p=S.top();
                S.pop();
                res.push_back(p->val);
                p=p->right;
            }
        }
        return res;
    }
原文地址:https://www.cnblogs.com/brianyi/p/10799513.html