遞迴實現二叉樹前中後遍歷
阿新 • • 發佈:2022-04-14
遞迴三要素:每次寫遞迴想到這三要素
1.確定遞迴函式的引數以及返回值
2.確定遞迴的出口
3.確定單層遞迴的邏輯
二叉樹結構體:
struct Treenode{ public: 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 traverpre(TreeNode* node, vector<int>& res) { if(!node) return; res.push_back(node->val); traverpre(node->left, res); traverpre(node->right, res); } vector<int> preorderTraversal(TreeNode* root) { vector<int> res; traverpre(root, res); return res; } };
中序遍歷:
class Solution { public: void traverord(TreeNode* node, vector<int>& res) { if(!node) return; traverord(node->left, res); res.push_back(node->val); traverord(node->right, res); } vector<int> inorderTraversal(TreeNode* root) { vector<int> res; traverord(root, res); return res; } };
後序遍歷:
class Solution {
public:
void traverpost(TreeNode* node, vector<int>& res)
{
if(!node)
return;
traverpost(node->left, res);
traverpost(node->right, res);
res.push_back(node->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
traverpost(root, res);
return res;
}
};