题解 | #实现二叉树先序,中序和后序遍历# C++ 解法,递归爆栈,改迭代通过

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

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

题解 | #实现二叉树先序,中序和后序遍历#
C++ 解法,递归爆栈,改迭代通过

/**
 * 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<vector<int>> ans;
    vector<int> path;
    void push() {
        ans.push_back(path);
        path.clear();
        return ;
    }
    void preOrder(TreeNode *node) {
        if (node == nullptr) return;
        stack<TreeNode *> sta;
        sta.push(node);
        while (!sta.empty()) {
            TreeNode *t = sta.top();
            sta.pop();
            path.push_back(t->val);
            if (t->right) sta.push(t->right);
            if (t->left) sta.push(t->left);
        }
        return ;
    }
    void inOrder(TreeNode *node) {
        if (node == nullptr) return ;
        stack<TreeNode *> sta;
        TreeNode *cur = node;
        while (cur || !sta.empty()) {
            if (cur) {
                sta.push(cur);
                cur = cur->left;
            } else {
                cur = sta.top();
                sta.pop();
                path.push_back(cur->val);
                cur = cur->right;
            }
        }
        return ;
    }
    void postOrder(TreeNode *node) {
        if (node == nullptr) return ;
        stack<TreeNode *> sta;
        sta.push(node);
        while (!sta.empty()) {
            TreeNode *t = sta.top();
            sta.pop();
            path.push_back(t->val);
            if (t->left) sta.push(t->left);
            if (t->right) sta.push(t->right);
        }
        reverse(path.begin(), path.end());
        return ;
    }
    vector<vector<int> > threeOrders(TreeNode* root) {
        preOrder(root);
        push();
        inOrder(root);
        push();
        postOrder(root);
        push();
        return ans;
    }
};
全部评论
递归没有爆栈
点赞 回复 分享
发布于 2021-09-21 11:17

相关推荐

今天 10:39
门头沟学院 Java
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-11 13:34
offe从四面八方来:我真的没时间陪你闹了
点赞 评论 收藏
分享
06-12 16:00
天津大学 Java
牛客30236098...:腾讯坏事做尽,终面挂是最破防的 上次被挂了后我连简历都不刷了
点赞 评论 收藏
分享
有没有佬投这个呀,怎么样呀求问
投递中科院空天信息创新研究院等公司10个岗位
点赞 评论 收藏
分享
评论
4
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务