144. 二叉树的前序遍历
程序员文章站
2024-01-10 21:10:10
...
方法一:递归
/**
* 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 {
private:
vector<int> res; //存储遍历数据
public:
vector<int> preorderTraversal(TreeNode* root) {
if(root){
res.push_back(root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
return res;
}
};
/**
* 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> res;
preTravel(root, res); //传递res参数保存返回值
return res;
}
private:
void preTravel(TreeNode* root,vector<int> &vc){
if(!root)
return;
vc.push_back(root->val);
preTravel(root->left,vc);
preTravel(root->right,vc);
}
};
方法二:迭代,栈
/**
* 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> res;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode *top=st.top();
st.pop();
if(top){
res.push_back(top->val);
st.push(top->right); //注意右子树先入栈,左子树后入栈
st.push(top->left);
}
}
return res;
}
};