题解 | #实现二叉树先序,中序和后序遍历# 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

相关推荐

4 收藏 评论
分享
牛客网
牛客企业服务