Chapter 7 Binary Trees || Section 2 Sequence Printing Exercises for Recursive Binary Trees

Please implement the preorder, inorder and postorder traversal and printing of the binary tree in a recursive way.

Given a root node root of a binary tree , please return the preorder, inorder and subsequent traversal of the binary tree in order (in the form of a two-dimensional array).

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/

class TreeToSequence {
public:
    vector<vector<int>> res;
    vector<int> vec;
    void PreOrder(TreeNode* root)
    {
        if(root)
        {
            vec.push_back(root->val);
            PreOrder(root->left);
            PreOrder(root->right);
        }
        return ;
    }
    void InOrder(TreeNode* root)
    {
        if(root)
        {
            InOrder(root->left);
            vec.push_back(root->val);
            InOrder(root->right);
        }
        return ;
    }
    void PostOrder(TreeNode* root)
    {
        if(root)
        {
            PostOrder(root->left);
            PostOrder(root->right);
            vec.push_back(root->val);
        }
        return ;
    }
    vector<vector<int> > convert(TreeNode* root) {
        // write code here
        if(root==NULL)
            return res;
        PreOrder(root);
        res.push_back(vec);
        vec.clear();
        InOrder(root);
        res.push_back(vec);
        vec.clear();
        PostOrder (root);
        res.push_back(vec);
        return res;
    }
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325280239&siteId=291194637