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]
.
/**
* 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> vec;
preOrder(root, vec);
return vec;
}
//递归写法
/*
void preOrder(TreeNode *root, vector<int> &path)
{
if (root)
{
path.push_back(root->val);
preOrder(root->left, path);
preOrder(root->right, path);
}
}
*/
//非递归写法
void preOrder(TreeNode *root, vector<int> &path)
{
stack<TreeNode *> TreeNodeStack;
while (root != NULL || !TreeNodeStack.empty())
{
while (root != NULL)
{
path.push_back(root->val);
TreeNodeStack.push(root);
root = root->left;
}
if (!TreeNodeStack.empty())
{
root = TreeNodeStack.top();
TreeNodeStack.pop();
root = root->right;
}
}
}
};