Skip to content

Instantly share code, notes, and snippets.

@zhoutuo
Created February 23, 2013 23:48
Show Gist options
  • Save zhoutuo/5021894 to your computer and use it in GitHub Desktop.
Save zhoutuo/5021894 to your computer and use it in GitHub Desktop.
Given a binary tree, return the inorder traversal of its nodes' values.
/**
* 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;
stack<TreeNode*> sta;
if(root == NULL) {
return result;
}
sta.push(root);
while(!sta.empty()) {
TreeNode* top = sta.top();
if(top->left != NULL) {
sta.push(top->left);
top->left = NULL;
} else {
result.push_back(top->val);
sta.pop();
if(top->right != NULL) {
sta.push(top->right);
}
}
}
return result;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment