递归法
/**
* 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 {
public:
void preorder(TreeNode*root,vector<int>&res){
if(!root)return;
res.push_back(root->val);
preorder(root->left,res);
preorder(root->right,res);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int>res{};
preorder(root,res);
return res;
}
};
迭代法
/**
* 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 {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int>res{};
if(!root)return res;
stack<TreeNode*>it;
it.push(root);
while(!it.empty()){
TreeNode* Node=it.top();
res.push_back(Node->val);
it.pop();
if(Node->right)it.push(Node->right);
if(Node->left)it.push(Node->left);
}
return res;
}
};
Morris法
Morris法利用叶节点的空余指针指向各个父节点,从而避免了采用stack存储节点信息,实现了O(n)的时间复制度,O(1)的空间复杂度。
/**
* 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 {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int>ret{};
if(!root)return ret;
TreeNode*cur=root;
TreeNode*mostRight;
while(cur){
if(cur->left){
mostRight=cur->left;
while(mostRight->right&&mostRight->right!=cur)mostRight=mostRight->right;
if(mostRight->right==nullptr){
ret.push_back(cur->val);
mostRight->right=cur;
cur=cur->left;
continue;
}
else{
mostRight->right=nullptr;
}
}
else{
ret.push_back(cur->val);
}
cur=cur->right;
}
return ret;
}
};