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].

Note: Recursive solution is trivial, could you do it iteratively?

/**
 * 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>result;
        travel(result,root);
        return result;
    }
    void travel(vector<int> & result,TreeNode* root)
    {
        if(root==NULL) return;
        travel(result,root->left);
        result.push_back(root->val);
        travel(result,root->right);
    }
};

 

posted @ 2014-05-29 17:11  erictanghu  阅读(88)  评论(0编辑  收藏  举报