【leetcode 94. 二叉樹的中序遍歷】解題報告

 

前往二叉樹的:前序,中序,後序 遍歷算法html

方法一:遞歸算法

    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;
    }

方法二:非遞歸spa

    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;
    }
相關文章
相關標籤/搜索