![leetcode - [7]Binary Tree Preorder Traversal leetcode - [7]Binary Tree Preorder Traversal](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
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]
.
思路:前序遍历,“根,左子树,右子树”
#include <iostream>
#include <vector>
#include <stack>
using namespace std; 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*> s;
if (!root) {
return res;
} s.push(root);
while(!s.empty()) {
TreeNode *p = s.top(); s.pop();
res.push_back(p->val);
if (p->right) {
s.push(p->right);
}
if (p->left) {
s.push(p->left);
}
}
return res;
}
}; int main() {
return ;
}