leetcode 二叉树的中序遍历(递归与非递归) 简单_递归

 

 

递归很简单,不说了。

非递归:用栈来模拟整个递归的过程,但是栈放一个 pair<TreeNode*, bool>,bool 为 false 表示当前这个节点并未向左延伸

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> ans;
        stack<pair<TreeNode*, bool>> stk;   // bool = false 表示向左扩展
        if(root) stk.push({root, false});
        while(!stk.empty()) {
            pair<TreeNode*, bool> &top = stk.top();
            if((!top.second && top.first -> left == nullptr) || top.second) {
                ans.emplace_back(top.first -> val);
                stk.pop();
                if (top.first -> right) stk.push({top.first -> right, false});
                continue;
            }
            if(!top.second) {
                top.second = true;
                stk.push({top.first -> left, false});
                continue;
            }
            if (top.first -> right) stk.push({top.first -> right, false});
        }
        return ans;
    }
};

 

另一种写法:

// leetcode 题解
public:
    vector<int> inorderTraversal1(TreeNode* root) {
        if (!root) return {};

        vector<int> res;
        stack<TreeNode*> s;
        TreeNode *curr = root;
        while (curr || !s.empty()) {
            while (curr) {
                s.push(curr);
                curr = curr->left;
            }

            TreeNode *node = s.top();
            res.push_back(node->val);
            s.pop();

            curr = node->right;
        }
        return res;
    }