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 preorderTraversal(TreeNode *root) { vector res; if(root==NULL)return res; stacksta; sta.push(root); while(!sta.empty()) { TreeNode *tmp=sta.top(); sta.pop(); res.push_back(tmp->val); if(tmp->right)sta.push(tmp->right); if(tmp->left)sta.push(tmp->left); } return res; }/**void preorder(vector &res, TreeNode * root){ if(root==NULL)return; res.push_back(root->val); preorder(res,root->left); preorder(res,root->right);} vector preorderTraversal(TreeNode *root) { vector res; preorder(res,root); return res; }*/};