递归遍历
cpp
/**
* 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 {
void traversal(TreeNode* root,vector<int>&res){
if(root==nullptr)
return ;
// traversal(root->left,res);
res.push_back(root->val);
traversal(root->left,res);
traversal(root->right,res);
}
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int>res;
traversal(root,res);
return res;
}
};
迭代遍历
cpp
/**
* 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;
stack<TreeNode*>sta;
if(root!=nullptr) sta.push(root);
while(!sta.empty()){
TreeNode *node=sta.top();
sta.pop();
res.push_back(node->val);
if(node->right!=nullptr)sta.push(node->right);
if(node->left!=nullptr)sta.push(node->left);
}
return res;
}
};
统一风格迭代遍历
cpp
/**
* 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> inorderTraversal(TreeNode* root) {
stack<TreeNode*>sta;
vector<int>res;
if(root!=nullptr) sta.push(root);
while(!sta.empty()){
TreeNode*node=sta.top();
if(node!=nullptr){
sta.pop();
if(node->right!=nullptr)sta.push(node->right);
sta.push(node);
sta.push(nullptr);
if(node->left!=nullptr)sta.push(node->left);
}else{
sta.pop();
node=sta.top();
res.push_back(node->val);
sta.pop();
}
}
return res;
}
};