94. Binary Tree Inorder Traversal

Given a binary tree, return theinordertraversal 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?

Trivial Solution: According to the definition of Inorder (O(n) time and O(n) space, for the function call stack)

class Solution {
    vector<int> answer;
public:
    vector<int> inorderTraversal(TreeNode* root) {

        inorderTraversalHelper(root);
        return answer;        
    }

    void inorderTraversalHelper(TreeNode * root){
        if(!root) return;
        inorderTraversalHelper(root->left);
        answer.push_back(root->val);
        inorderTraversalHelper(root->right);
    }
};

Thoughts

  1. Using Stack to keep track path

  2. *Morris traversal

Code Using Stack: (O(n) time and O(n) space)

Code with Morris Traversal: O(n) time and O(1) space (two assisting pointers)!

psudo-code (Thanks monkeykingyan's solution)

Code

Talonj @ Stackoverflow explaination:

Special Thanks jianchaolifighter for the reference

Last updated

Was this helpful?