递归

/**
 * struct TreeNode {
 *    int val;
 *    struct TreeNode *left;
 *    struct TreeNode *right;
 *    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型vector
     */
    vector<int> inorderTraversal(TreeNode* root) {
        // write code here
        inOrder(root);
        return res;
    }
    vector<int> res;
    void inOrder(TreeNode* root){
        if(root == NULL) return;
        inOrder(root -> left);
        res.push_back(root -> val);
        inOrder(root -> right);
    }
};

迭代

/**
 * struct TreeNode {
 *    int val;
 *    struct TreeNode *left;
 *    struct TreeNode *right;
 *    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型vector
     */
    vector<int> inorderTraversal(TreeNode* root) {
        // write code here
        TreeNode* p = root;
        stack<TreeNode*> stk;
        vector<int> res;
        while(p != NULL || !stk.empty()){
            while(p != NULL){
                stk.push(p);
                p = p -> left;
            }
            if(!stk.empty()){
                p = stk.top();
                res.push_back(p -> val); stk.pop();
                p = p -> right;
            }
        }
        return res;
    }
};