/**
* 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 traversal(TreeNode *cur,vector<int> &a)
{
if(cur==nullptr) return;
a.push_back(cur->val);
traversal(cur->left,a);
traversal(cur->right,a);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> a;
traversal(root,a);
return a;
}
//非递归
vector<int> preorderTraversal(TreeNode* root)
{
stack<TreeNode*> st;
vector<int> result;
if(root==NULL) return result;
st.push(root);
while(!st.empty()){
TreeNode* node=st.top();
st.pop();
result.push_back(node->val);
if(node->right) st.push(node->right);
if(node->left) st.push(node->left);
}
return result;
}
};
标签:node,right,TreeNode,val,递归,前序,st,二叉树,left
From: https://blog.csdn.net/qq_60510847/article/details/141501347