数据结构|二叉树前序、中序、后序遍历C++代码实现(递归)

二叉树的前序遍历

/**
 * 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 preorder(TreeNode* root,vector &res)
    {
        if(root==nullptr)
        {
            return;
        }
         res.push_back(root->val);
         preorder(root->left,res);
         preorder(root->right,res);
       
    }
    vector preorderTraversal(TreeNode* root) {
        vector res;
       preorder(root,res);
       return res;
    }

       
};

二叉树的中序遍历

/**
 * 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 inorder(TreeNode* root, vector& res) {
        if (!root) {
            return;
        }
        inorder(root->left, res);
        res.push_back(root->val);
        inorder(root->right, res);
    }
    vector inorderTraversal(TreeNode* root) {
        vector res;
        inorder(root, res);
        return res;
    }
};

二叉树的后序遍历

/**
 * 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 postorder(TreeNode* root,vector &res)
    {
        if(root==nullptr)
        {
            return;
        }
        postorder(root->left,res);
        postorder(root->right,res);
        res.push_back(root->val);
    }
    vector postorderTraversal(TreeNode* root) {
        vector res;
        postorder(root, res);
        return res;
    }
};

        可以看出上面三种遍历使用的是同一种模板,只要记住模板即可。

你可能感兴趣的:(数据结构,c++,开发语言,数据结构)