0094.二叉树的中序遍历

https://leetcode-cn.com/problems/binary-tree-inorder-traversal

原题

给定一个二叉树的根节点 root ,返回它的 中序 遍历。

示例 1:
0094. 二叉树中序遍历 - 图1

  1. 输入:root = [1,null,2,3]
  2. 输出:[1,3,2]

示例 2:


输入:root = []
输出:[]

示例 3:


输入:root = [1]
输出:[1]

示例 4:
0094. 二叉树中序遍历 - 图2


输入:root = [1,2]
输出:[2,1]

示例 5:
0094. 二叉树中序遍历 - 图3


输入:root = [1,null,2]
输出:[1,2]

提示:

  • 树中节点数目在范围 [0, 100] 内
  • -100 <= Node.val <= 100

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

标签
栈 树 深度优先搜索 二叉树

思路

迭代写法:

不断加入当前节点的左节点

每当弹一个节点时,也不断加入左节点

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        stack<TreeNode *> s;
        TreeNode *p = root;
        vector<int> res;

        while(p){
            s.push(p);
            p = p->left;
        }

        while(!s.empty()){
            res.push_back(s.top()->val);

            TreeNode *right = s.top()->right;
            s.pop();

            while(right){
                s.push(right);
                right = right->left;
            }
        }
        return res;
    }
};

迭代写法:

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        if (!root) return res;

        stack<TreeNode*>s;
        // s.push(root);
        TreeNode * cur = root;
        while(cur || !s.empty()){
            if(cur){
                s.push(cur);
                cur = cur->left;
            }else{
                // TreeNode *top = s.top();
                cur = s.top();
                s.pop();

                // res.push_back(top->val);
                res.push_back(cur->val);

                // if(!top->right) s.push(top->right);
                cur = cur->right;
            }
        }
        return res;
    }
};
// 注释中是原先错误的写法

需要一个指针访问,栈来处理

只要指针cur不为空,cur进栈,cur 变为左边的元素
否则:
cur 指向栈顶,弹出,加入结果中
cur 变为右边的元素