zoukankan      html  css  js  c++  java
  • Leetcode.94.二叉树的中序遍历

    94.二叉树的中序遍历

    递归遍历

    迭代遍历

    /**
     * Definition for a binary tree node.
     * 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) {
            stack<TreeNode*> lt;
            vector<int> ans;
            TreeNode* curr = root;
            while(!lt.empty() || curr!=nullptr){
                while(curr != nullptr){
                    lt.push(curr);
                    curr=curr->left;
                }
                TreeNode* p = lt.top();
                lt.pop();
                ans.push_back(p->val);
                if(p->right != nullptr)
                {
                    curr = p->right;
                }
            }
            return ans;
        }
    };
    

    莫里斯遍历

    莫里斯遍历主要思想是将中间根节点放到左子树的最右侧节点。
    可以从运行时间和使用内存看出来,确实莫里斯遍历要由于普通迭代。

    /**
     * Definition for a binary tree node.
     * 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> ans;
            TreeNode* curr=root;
            while(curr!=nullptr)
            {
                if(curr->left == nullptr){
                    ans.push_back(curr->val);
                    curr=curr->right;
                }
                else{
                    TreeNode* p = curr->left;
                    while(p->right!=nullptr){
                        p=p->right;
                    }
                    p->right= curr;
                    TreeNode* t=curr;
                    curr = curr->left;
                    t->left = nullptr;
                }
            }
            return ans;
        }
    };
    
  • 相关阅读:
    dd的用法
    od的用法
    Windows 7安装Oracle 10g的方法
    Ubuntu下的iptux和Windows下的飞秋互传文件
    c++ 12
    c++ 11
    c++ 10
    c++ 09
    c++ 08
    c++ 07
  • 原文地址:https://www.cnblogs.com/huangdong2000/p/12211017.html
Copyright © 2011-2022 走看看