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;
        }
    };
    
  • 相关阅读:
    CentOS7安装docker
    CentOS7安装maven
    centos下使用ifconfig命令无法得到ip地址的解决方案
    Elasticsearch 2.3.5 之Head插件安装
    CentOS7中yum源结构解析
    EXT.NET Combox下拉Grid
    转 Refresh Excel Pivot Tables Automatically Using SSIS Script Task
    SQL Server Integration Services SSIS最佳实践
    PowerBI
    [XAF] Llamachant Framework Modules
  • 原文地址:https://www.cnblogs.com/huangdong2000/p/12211017.html
Copyright © 2011-2022 走看看