C/C++教程

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

本文主要是介绍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 No.94 Binary Tree Inorder Traversal二叉树中序遍历(c++实现)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!