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

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

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

递归实现二叉树的前序、中序和后序遍历

/**
 * 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<>>
     */
    void preOrder(vector<int>& ans, TreeNode* root) {
        if (root != nullptr) {
            ans.push_back(root->val);
            preOrder(ans, root->left);
            preOrder(ans, root->right);
        }
    }

    void midOrder(vector<int>& ans, TreeNode* root) {
        if (root != nullptr) {
            midOrder(ans, root->left);
            ans.push_back(root->val);
            midOrder(ans, root->right);
        }
    }

    void postOrder(vector<int>& ans, TreeNode* root) {
        if (root != nullptr) {
            postOrder(ans, root->left);
            postOrder(ans, root->right);
            ans.push_back(root->val);
        }
    }

    vector<vector<int> > threeOrders(TreeNode* root) {
        // write code here
        vector<vector<int> > threeorders;
        vector<int> pre, mid, post;
        preOrder(pre, root);
        midOrder(mid, root);
        postOrder(post, root);
        threeorders.push_back(pre);
        threeorders.push_back(mid);
        threeorders.push_back(post);
        return threeorders;
    }
};
全部评论

相关推荐

11-09 01:22
已编辑
东南大学 Java
高级特工穿山甲:羡慕,我秋招有家企业在茶馆组织线下面试,约我过去“喝茶详谈”😢结果我去了发现原来是人家喝茶我看着
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务