• 周练(1)94. 二叉树的中序遍历


    94. 二叉树的中序遍历

    给定一个二叉树,返回它的中序 遍历。

    示例:

    输入: [1,null,2,3]
       1
        
         2
        /
       3
    
    输出: [1,3,2]
    

    递归解法:

    /*
     * @lc app=leetcode.cn id=94 lang=cpp
     *
     * [94] 二叉树的中序遍历
     */
    
    // @lc code=start
    /**
     * 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;
            inorder(root, ans);
            return ans;
        }
    
        void inorder(TreeNode *root, vector<int>& ans) {
            if (root == nullptr) {
                return;
            }
            inorder(root->left, ans);
            ans.push_back(root->val);
            inorder(root->right, ans);
        }
    };
    

    迭代写法:

    /*
     * @lc app=leetcode.cn id=94 lang=cpp
     *
     * [94] 二叉树的中序遍历
     */
    
    // @lc code=start
    /**
     * 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*> S;
            vector<int> v;
            TreeNode *rt = root;
            while (rt || S.size())
            {
                while (rt) {
                    S.push(rt);
                    rt = rt->left;
                }
                rt = S.top(); S.pop();
                v.push_back(rt->val);
                rt = rt->right;
            }
            return v;
        }
    
    };
    // @lc code=end
    
  • 相关阅读:
    Iconfont在Vue中的使用
    yarn安装依赖报错
    动漫
    伤痛的魅力。绷带男子特辑
    记STM32F103C8T6+STLINK下载器在Keil中的设置
    JQuery浮动对象插件
    树莓派RTL8723BU_LINUX驱动安装
    python虚拟环境相关设置备忘
    解决树莓派控制台命令行乱码
    python模块wifi使用小记
  • 原文地址:https://www.cnblogs.com/douzujun/p/13665081.html
Copyright © 2020-2023  润新知