Monday, June 23, 2014

Binary Tree Inorder traversal -- Leetcode

Question:
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
   1
    \
     2
    /
   3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
Answer:
* 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) {
        vector<int> res;
        if(!root)return res;
        
        stack<TreeNode*> stk;
        TreeNode *cur = root;
             
        while(!stk.empty() || cur){
            if(cur){              
                stk.push(cur);
                cur= cur->left;     //If left child != NULL, will push continuously left child into stack.
            }
            else{
                cur= stk.top();
                stk.pop();
                res.push_back(cur->val);
                cur= cur->right;
            }
        }
        return res;
    }

};

No comments:

Post a Comment