题目来源:https://leetcode.cn/problems/binary-tree-preorder-traversal/description/
C++题解1:递归算法。注意递归函数的参数和返回值、终止条件、单层递归的逻辑。
递归函数的参数是当前指针和用来存放的vector,注意vector要加&引用;终止条件为当前遍历节点为空;前序遍历是指中间节点在前面,即中左右。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
void search(TreeNode* cur, vector<int>& result){
if(cur == nullptr) return;
result.push_back(cur->val);
search(cur->left, result);
search(cur->right, result);
}
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
search(root, result);
return result;
}
};
C++题解2:迭代遍历。使用栈实现。
由于前序遍历是中左右,那对应的入栈顺序就应该是右左中,不过中可以不入栈,直接获取其val进行保存;当遇到中为null时,意味着没有左右子树,此时只要将该节点pop出来就好。
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> store;
vector<int> result;
TreeNode* cur = root, next;
while(cur != nullptr || !store.empty()){
if(cur != nullptr){
store.push(cur->right);
store.push(cur->left);
result.push_back(cur->val);
}
cur = store.top();
store.pop();
}
return result;
}
};
C++提交3:统一迭代法。用空节点来标记待处理的中间节点。参照代码随想录
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> store;
vector<int> result;
TreeNode* cur = root;
if(cur != nullptr) store.push(cur);
while(!store.empty()){
cur = store.top();
if(cur != nullptr){
store.pop();
if(cur->right != nullptr) store.push(cur->right);
if(cur->left != nullptr) store.push(cur->left);
store.push(cur);
store.push(nullptr);
}
else{
store.pop();
cur = store.top();
result.push_back(cur->val);
store.pop();
}
}
return result;
}
};