Front, middle and back order of binary tree

Preorder traversal of binary tree

class Solution {
    
    
public:
    vector<int> preorderTraversal(TreeNode* root) {
    
    
        vector<int>res;
         Traversal(root,res);
         return res;
        
    }
    void Traversal(TreeNode*root,vector<int>&res)
    {
    
    
        if(!root) return ;
        res.push_back(root->val);
        Traversal(root->left,res);
        Traversal(root->right,res);
    }
};

Post-order traversal of binary tree

class Solution {
    
    
public:
    vector<int> postorderTraversal(TreeNode* root) {
    
    
        vector<int>res;
         Traversal(root,res);
         return res;
        
    }
    void Traversal(TreeNode*root,vector<int>&res)
    {
    
    
        if(!root) return ;
        Traversal(root->left,res);
        Traversal(root->right,res);
        res.push_back(root->val);
    }
};

In-order traversal of binary tree

class Solution {
    
    
public:
    vector<int> inorderTraversal(TreeNode* root) {
    
    
        vector<int>res;
         Traversal(root,res);
         return res;
        
    }
    void Traversal(TreeNode*root,vector<int>&res)
    {
    
    
        if(!root) return ;
        Traversal(root->left,res);
        res.push_back(root->val);
        Traversal(root->right,res);
        
    }
};

Then the summary:
1. To determine the parameters and return value of the recursive function
2. Break out of the recursion conditions
3. Recursion to perform operations
Take the above-mentioned pre-order traversal as an example
1.

void traversal(TreeNode* cur, vector<int>& vec)
if(!root) return ;
 res.push_back(root->val);//中
 Traversal(root->left,res);//左
 Traversal(root->right,res);//右

Note that this is the content to be prepared in the recursive function! ! ! Don’t write it in the main function,
so just change the recursive function operation later.

Guess you like

Origin blog.csdn.net/qq_44808694/article/details/111415722