阔别了已久的leetcode 又回来了。
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 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)
{
vector<int> res;
stack<TreeNode*> m_stack;
if (root == NULL) return res;
m_stack.push(root);
while (!m_stack.empty())
{
TreeNode* tmp = m_stack.top();
res.push_back(tmp->val);
m_stack.pop();
if (tmp->right) m_stack.push(tmp->right);
if (tmp->left) m_stack.push(tmp->left);
}
}
};