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?

C++:
01 /**
02  * Definition for binary tree
03  * struct TreeNode {
04  *     int val;
05  *     TreeNode *left;
06  *     TreeNode *right;
07  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
08  * };
09  */
10 class Solution {
11 public:
12     vector<int> inorderTraversal(TreeNode *root) {
13         // Start typing your C/C++ solution below
14         // DO NOT write int main() function
15         vector<int> result;
16         if(root==NULL)
17             return result;
18         stack<TreeNode*> P;
19         P.push(root);
20         while(!P.empty())
21         {
22             TreeNode* tmp=P.top();
23             P.pop();
24             if(tmp->left!=NULL)
25             {
26                 TreeNode* left=tmp->left;
27                 tmp->left=NULL;
28                 P.push(tmp);
29                 P.push(left);
30             }
31             else
32             {
33                 result.push_back(tmp->val);
34                 if(tmp->right!=NULL)
35                 {
36                     P.push(tmp->right);
37                 }
38             }
39         }
40         return result;
41     }
42 };
Advertisements
This entry was posted in Stack and Queue, Tree. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s