0ms cpp solution


  • 0
    Z
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    #include <stack>
    class Solution {
    public:
        vector<int> inorderTraversal(TreeNode* root) {
            if (root == NULL) {
                return std::vector<int>(0);
            }
            std::vector<int> ret;
            std::stack<TreeNode *> buf;
            buf.push(root);
            while (!buf.empty()) {
                auto tmp = buf.top();
                buf.pop();
                if (tmp->left == NULL && tmp->right == NULL) {
                    ret.push_back(tmp->val);
                } else {
                    if (tmp->right != NULL) {
                        buf.push(tmp->right);
                    }
                    buf.push(new TreeNode(tmp->val));
                    if (tmp->left != NULL) {
                        buf.push(tmp->left);
                    }
                }
            }
            return ret;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.