Binary Tree Inorder Traversal

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

Solution:

Recursive solution is trivial.

Iterative solution: Traverse from root to the leftmost until you hit the bottom level, use a stack to store the previous nodes. Then go back by pop the stack and go to the right.

See here to get a perfect explanation.

The following codes pass the LeetCode Online Large Judge.

Recursive version:


/**
 * Definition for binary tree
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> list;
        TraversalHelper(root, list);
        return list;
    }
    
    void TraversalHelper(TreeNode *root, vector<int> &list) {
        if (root == NULL) return;
        TraversalHelper(root->left, list);
        list.push_back(root->val);
        TraversalHelper(root->right, list);
    }
};

Iterative version:


/**
 * Definition for binary tree
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> list;
        stack<TreeNode*> s;
        TreeNode *current = root;
        while (!s.empty() || current) {
            if (current) {
                s.push(current);
                current = current->left;
            }
            else {
                list.push_back(s.top()->val);
                current = s.top()->right;
                s.pop();
            }
        }
        return list;
    }
};

Comments

Popular posts from this blog

Maximum Gap

[ITint5] Maximum Subarray for a Circular Array

[CC150] Chapter 8 Object-Oriented Design