Created
November 6, 2013 16:44
-
-
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/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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