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

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

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;
    }
};
全部评论

相关推荐

点赞 评论 收藏
分享
牛客771574427号:恭喜你,华杰
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务