94 Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values.
For example:

Given binary tree [1,null,2,3],
   1
    \
     2
    /
   3

return [1,3,2].

  • Note: Recursive solution is trivial, could you do it iteratively?

Solution:
Use an additional tag array to record the status of the nodes

/**
 * 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*> s_tnode;
        stack<int> s_tag;
        s_tnode.push(root);
        s_tag.push(0);
        while ( ! s_tnode.empty() ) {
            TreeNode* tnode = s_tnode.top();
            int tag = s_tag.top();
            if ( tag == 0 ) {
                s_tag.pop();
                s_tag.push(tag+1);
                if ( tnode->left != NULL ) {
                    s_tnode.push(tnode->left);
                    s_tag.push(0);
                }
            }
            if ( tag == 1 ) {
                s_tnode.pop();
                s_tag.pop();
                res.push_back(tnode->val);
                if ( tnode->right != NULL ) {
                    s_tnode.push(tnode->right);
                    s_tag.push(0);
                }
            }
        }
        return res;
    }
};
// Morris???

results matching ""

    No results matching ""