【Leetcode】94.二叉树的中序遍历C++(莫里斯遍历法)

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

#include "iostream"

#include "vector"

using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution
{
public:
    vector<int> inorderTraversal(TreeNode *root)
    {
        vector<int> nodes;
        while (root)
        {
            if (root->left)
            {
                // 有左子树
                // 使得current成为左子树最右侧节点的右子节点
                TreeNode *pre = root->left, *next = pre;
                while (pre->right)
                {
                    pre = pre->right;
                }
                // root换成root的左子节点
                pre->right = root;
                root->left = NULL;
                root = next;
            }
            else
            {
                // 没有左子树
                nodes.push_back(root->val); // 将current添加到输出
                root = root->right;         // 进入右子树
            }
        }
        return nodes;
    }
};
发布了103 篇原创文章 · 获赞 128 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44936889/article/details/104101358