Monday, June 16, 2014

Binary Tree Inorder Traversal (stack) -- Leetcode

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?

OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
   1
  / \
 2   3
    /
   4
    \
     5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

Answer:
* Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
1. Using stack, iteratively.
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;            //Important!
            }
        }
        return res;
    }

};

2.Recursively:
vector<int> inorderTraversal(TreeNode *root) {  
     vector<int> result;  
     inorderTra(root, result);  
     return result;  
} 
void inorderTra(TreeNode* node, vector<int> &result) {  
     if(!node) return; 
     inorderTra(node->left, result);  
     result.push_back(node->val);      
     inorderTra(node->right, result);  
}  

No comments:

Post a Comment