Created
January 21, 2019 00:51
-
-
Save zhangxiaomu01/af25e34b28b9714f8a1feb2a2139d28c to your computer and use it in GitHub Desktop.
This file contains 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 a binary tree node. | |
* 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) { | |
vector<int> res; | |
stack<TreeNode*> st; | |
if(root == NULL) | |
return res; | |
st.push(root); | |
while(!st.empty()){ | |
TreeNode* temp = st.top(); | |
st.pop(); | |
res.push_back(temp->val); | |
if(temp->right != NULL) | |
st.push(temp->right); | |
if(temp->left != NULL) | |
st.push(temp->left); | |
} | |
return res; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment