实现二叉树先序,中序和后序

题目描述
分别按照二叉树先序,中序和后序打印所有的节点。

示例
输入
{1,2,3}
输出
[[1,2,3],[2,1,3],[2,3,1]]

思路描述:
总体是用递归实现,但要注意细节,利用vector可以更好得存储数据,且vector<vector>可存储二维数组,auto可以根据实际类型进行设定,

代码描述:

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 the root of binary tree
     * @return int整型vector<vector<>>
     */
    vector<int> preOrder(TreeNode* root)
    {
        vector<int> res;
        if (root == NULL) return res;
        else{
            res.push_back(root->val);
            for (auto v: preOrder(root->left))
                res.push_back(v);
            for (auto v: preOrder(root->right))
                res.push_back(v);
        }
    }
    
        vector<int> midOrder(TreeNode* root)
    {
        vector<int> res;
        if (root == NULL) return res;
        else{
            for (auto v: preOrder(root->left))
                res.push_back(v);
            res.push_back(root->val);
            for (auto v: preOrder(root->right))
                res.push_back(v);
        }
    }
    
        vector<int> postOrder(TreeNode* root)
    {
        vector<int> res;
        if (root == NULL) return res;
        else{
            for (auto v: preOrder(root->left))
                res.push_back(v);
            for (auto v: preOrder(root->right))
                res.push_back(v);
            res.push_back(root->val);
        }
    }
    
    
    vector<vector<int> > threeOrders(TreeNode* root) {
        // write code here
        vector<int> pre = preOrder(root);
        vector<int> mid = midOrder(root);
        vector<int> post = postOrder(root);
        
        vector<vector<int>> res;
        res.push_back(pre);
        res.push_back(mid);
        res.push_back(post);
        return res;
    }
};
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页