Skip to content

Instantly share code, notes, and snippets.

@eclipselu
Created November 6, 2013 16:44
Show Gist options
  • Select an option

  • Save eclipselu/7339572 to your computer and use it in GitHub Desktop.

Select an option

Save eclipselu/7339572 to your computer and use it in GitHub Desktop.
LeetCode: Binary Tree Preorder Traversal http://oj.leetcode.com/problems/binary-tree-preorder-traversal/
/**
* 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> preorderTraversal(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<int> res;
if (root == NULL)
return res;
stack<TreeNode *> st;
st.push(root);
while (!st.empty()) {
TreeNode *cur = st.top();
st.pop();
res.push_back(cur->val);
if (cur->right)
st.push(cur->right);
if (cur->left)
st.push(cur->left);
}
return res;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment