Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree [1,null,2,3]
,
1 \ 2 / 3
return [1,2,3]
.
/**
* 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> v;
//preTraversal_recursion(root,v);
preTraversal_iterative(root,v);
return v;
}
//使用递归的方法
void preTraversal_recursion(TreeNode* root,vector<int> &v)
{
if(root!=NULL)
{
v.push_back(root->val);
preTraversal_recursion(root->left,v);
preTraversal_recursion(root->right,v);
}
}
//使用迭代方法,运用堆栈
void preTraversal_iterative(TreeNode* root,vector<int> &v)
{
if (root==NULL)
return;
stack<TreeNode *> s;
s.push(root);
while (!s.empty())
{
TreeNode *temp = s.top();
v.push_back(temp->val);
s.pop();
if (temp->right!=NULL)
s.push(temp->right);
if (temp->left!=NULL)
s.push(temp->left);
}
}
};