94.Binary Tree Inorder Traversal

// Recursion
class Solution {
public:
    vector inorderTraversal(TreeNode *root) {
        vector res;
        inorder(root, res);
        return res;
    }
    void inorder(TreeNode *root, vector &res) {
        if (!root) return;
        if (root->left) inorder(root->left, res);
        res.push_back(root->val);
        if (root->right) inorder(root->right, res);
    }
};
class Solution {
public:
    vector inorderTraversal(TreeNode* root) {
        vector res;
        stack s;
        TreeNode *p = root;
        while (!s.empty() || p) {
            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/smallredness/p/10676555.html

你可能感兴趣的:(94.Binary Tree Inorder Traversal)