题解 | C++ #实现二叉树先序,中序和后序遍历#

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

http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 the root of binary tree
     * @return int整型vector<vector<>>
     */
    vector<vector<int> > threeOrders(TreeNode* root) { //返回二维数组
        // 分别调用三个遍历函数,分别尾***二维数组
        vector<vector<int> >  res;
        po(root);
        res.push_back(a);
        io(root);
        res.push_back(b);
        pto(root);
        res.push_back(c);
        return res;
    }
    //以前序遍历序列为例,先定义一个一维数组,默写前序递归框架,每个节点做的就是向一维数组中尾插。
    vector<int> a;
    vector<int> po(TreeNode *root){
        if(root==nullptr)  return{};
        a.push_back(root->val);
        if(root->left) po(root->left);
        if(root->right) po(root->right);
        return a;
    }
    //中序和后序同理
    vector<int> b;
    vector<int> io(TreeNode *root){
        if(root==nullptr)  return{};
        if(root->left) io(root->left);
        b.push_back(root->val);
        if(root->right) io(root->right);
        return b;
    }
    vector<int> c;
    vector<int> pto(TreeNode *root){
        if(root==nullptr)  return{};
        if(root->left) pto(root->left);
        if(root->right) pto(root->right);
        c.push_back(root->val);
        return c;
    }
};
全部评论

相关推荐

02-12 00:59
已编辑
哈尔滨工业大学 产品经理
华为 软件开发岗 20.6*16薪 本科
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务