Problem
Given a binary tree, return the preorder traversal of its nodes' values.For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
Code
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> result; stack<TreeNode *> st; if(root) st.push(root); while(!st.empty()){ TreeNode *node = st.top(); st.pop(); result.push_back(node->val); if(node->right) st.push(node->right); if(node->left) st.push(node->left); } return result; }
No comments:
Post a Comment