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?
/** * 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> ret; if(root==NULL)return ret; stack<TreeNode*> st; st.push(root); TreeNode* ptr; while(st.size()!=0){ ptr=st.top(); st.pop(); ret.push_back(ptr->val); if(ptr->right!=NULL)st.push(ptr->right); if(ptr->left!=NULL)st.push(ptr->left); } return ret; } };