题目:
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> rtn;
stack<TreeNode*> stc;
if (root) {
stc.push(root);
}
while (!stc.empty()) {
TreeNode *top = stc.top();
rtn.push_back(top->val);
stc.pop();
if (top->right) {
stc.push(top->right);
}
if (top->left) {
stc.push(top->left);
}
}
return rtn;
}
};