Saturday, November 9, 2013

Binary Tree Inorder Traversal [Leetcode]

In the previous post, we talked about the binary tree postorder traversal. Here the solution to the inorder traversal is similar to the second solution of the postorder traversal. The basic idea is to traverse the tree in the depth first fashion; print the node if (1) its left children has been traversed or (2) it has no children. To indicate the direction of traversing (down or up), we use a pointer pre to denote the previously-traversed node, and a pointer cur to denote the node we are traversing right now. [see 1 and 2 for other good solutions]
/**
 * 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> ret;
        if(root==NULL)
            return ret;
        stack<TreeNode*> st;
        TreeNode* pre = NULL;
        TreeNode* cur = NULL;
        st.push(root);
        while(!st.empty()){
            //Traversing down the tree
            cur = st.top();
            if(pre==NULL || cur==pre->left || cur==pre->right){
                if(cur->left!=NULL)
                    st.push(cur->left);
                else
                {
                    ret.push_back(cur->val);
                    if(cur->right!=NULL)
                        st.push(cur->right);
                    else
                        st.pop();
                }
            }
            //Traversing up the tree from left
            else if(cur->left==pre){
                ret.push_back(cur->val);
                if(cur->right!=NULL)
                    st.push(cur->right);
                else
                    st.pop();
            }                
            //Traversing up the tree from right
            else if(cur->right==pre)
                st.pop();
            //Keep track of the previously traversed node
            pre = cur;
        }
        return ret;
    }
}; 

No comments:

Post a Comment