94. 二叉树的中序遍历/C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        if(root==NULL)
            return res;
        
        stack<TreeNode*> stack;
        TreeNode* cur = root;
        while(cur!=NULL || !stack.empty()){
            while(cur!=NULL){
                stack.push(cur);
                cur=cur->left;
            }
            cur = stack.top();
            stack.pop();
            res.push_back(cur->val);
            cur=cur->right;
        }
        return res;
    }
};

相关文章: