Leetcode No.94 Binary Tree Inorder Traversal二叉树中序遍历(c++实现)

1. 题目

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

2. 分析

2.1 迭代法

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> ans;
        stack<TreeNode*> todo;//定义一个栈,先入后出
        while (root != nullptr || todo.empty() == false) {
            while (root) {//将左子树依次压入栈内
                todo.push(root);
                root = root->left;
            }

            root = todo.top();
            todo.pop();
            ans.push_back(root->val);

            root = root->right;
        }
        return ans;
    }
};

2.2 递归法

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> ans;
        inorder(root, ans);//递归求解
        return ans;
    }
private:
    void inorder(TreeNode* root, vector<int>& ans) {
        if (root == nullptr) { return; }
        inorder(root->left, ans);
        ans.push_back(root->val);
        inorder(root->right, ans);
    }
};

2.3 Morris莫尔斯算法

算法详解参考:https://zhuanlan.zhihu.com/p/101321696

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> nodes;
        while (root) {
            if (root -> left) {
                TreeNode* pre = root -> left;
                while (pre -> right && pre -> right != root) {
                    pre = pre -> right;
                }
                if (!pre -> right) {
                    pre -> right = root;
                    root = root -> left;
                } else {
                    pre -> right = NULL;
                    nodes.push_back(root -> val);
                    root = root -> right;
                }
            } else {
                nodes.push_back(root -> val);
                root = root -> right;
            }
        }
        return nodes;
    }
};

代码参考:https://leetcode.com/problems/binary-tree-inorder-traversal/discuss/31231/C%2B%2B-Iterative-Recursive-and-Morris

上一篇:类中函数相互调用


下一篇:leetcode 从前序与中序序列构造二叉树 中等