Saturday, February 23, 2013

Binary Tree Inorder Traversal

/*
Binary Tree Inorder Traversal
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].
*/
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void inorderTraversal(TreeNode *node, vector<int> & result){
      if(node==NULL) return;
      inorderTraversal(node->left, result);
      result.push_back(node->val);
      inorderTraversal(node->right, result);
    }
    vector<int> inorderTraversal(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> result;
        inorderTraversal(root, result);
        return result;
    }
};

//Non-recursive one
/**
 * 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> result;
        if(root==NULL) return result;
        stack<TreeNode*> s;
        TreeNode *curr = root;
        while((curr!=NULL) || (!s.empty())){
         if(curr!=NULL){
          s.push(curr);
          curr=curr->left;
         }
         else{
          curr = s.top();
          result.push_back(curr->val);
          s.pop();
          curr=curr->right;
         }
        }
        return result;
    }
};

No comments:

Post a Comment