Inorder Traversal Non-recursion

code

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Inorder in vector which contains node values.
     */
public:
    vector<int> inorderTraversal(TreeNode *root) {
        // write your code here
        vector<int> res;
        if(root == NULL)
        {
            return res;
        }

        TreeNode* p = root;
        vector<TreeNode*> stack;
        while(p != NULL || !stack.empty())
        {
            while(p != NULL)
            {
                stack.push_back(p);
                p = p->left;
            }
            p = stack.back();
            stack.pop_back();
            res.push_back(p->val);
            p = p->right;
        }

        return res;
    }
};

results matching ""

    No results matching ""