leetcode - [7]Binary Tree Preorder Traversal

时间:2023-03-10 02:04:08
leetcode - [7]Binary Tree Preorder Traversal

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 ;
}