赞
踩
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x):val(x),left(nullptr),right(nullptr){}
TreeNode(int x,TreeNode* left,TreeNode* right):val(x),left(left),right(left){}
};
递归
class Solution {
public:
void traverse(TreeNode* t,vector<int>& ans){
if(t==nullptr) return;
ans.push_back(t->val);
traverse(t->left,ans);
traverse(t->right,ans);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ans;
traverse(root,ans);
return ans;
}
};
迭代
class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int> ans; stack<TreeNode*>s; if(root==nullptr) return ans; s.push(root); while(!s.empty()){ TreeNode* p=s.top(); ans.push_back(p->val); s.pop(); if(p->right!=nullptr) s.push(p->right); if(p->left!=nullptr) s.push(p->left); } return ans; } };
递归
class Solution { public: void inorder(TreeNode* root, vector<int>& res) { if (root==nullptr) { return; } inorder(root->left, res); res.push_back(root->val); inorder(root->right, res); } vector<int> inorderTraversal(TreeNode* root) { vector<int> res; inorder(root, res); return res; } };
递归
class Solution {
public:
void traverse(TreeNode* t,vector<int>& ans){
if(t==nullptr) return;
traverse(t->left,ans);
traverse(t->right,ans);
ans.push_back(t->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ans;
traverse(root,ans);
return ans;
}
};
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。