Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree [1,null,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> ret;
if (root != nullptr)
reSolver(root, ret);
return ret;
}
private:
void reSolver(TreeNode* root, vector<int>& ret) {
ret.emplace_back(root->val);
if (root->left != nullptr) {
reSolver(root->left, ret);
}
if (root->right != nullptr) {
reSolver(root->right, ret);
}
}
};
迭代
/**
* 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> ret;
stack<TreeNode*> s;
TreeNode* p = root;
while (p != nullptr || !s.empty()) {
if (p != nullptr) {
ret.emplace_back(p->val);
s.push(p);
p = p->left;
} else {
TreeNode* r = s.top();
s.pop();
p = r->right;
}
}
return ret;
}
};