uacs2024

导航

leetcode94-二叉树的中序遍历

94. 二叉树的中序遍历

迭代法,看别人的代码的,还需要琢磨一下

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> sss;
        TreeNode* t=root;
        while(!sss.empty()||t!=nullptr)
        {
            if(t!=nullptr)
            {
                sss.push(t);
                t=t->left;
            }
            else
            {
                t = sss.top();
                sss.pop();
                res.push_back(t->val);
                t=t->right;
            }
        }
        return res;
    }
};

 

递归法,没什么好说的。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> res;
    void Tracking(TreeNode* root)
    {
        if(root==nullptr) return;
        Tracking(root->left);
        res.push_back(root->val);
        Tracking(root->right);
    }
    vector<int> inorderTraversal(TreeNode* root) {
        Tracking(root);
        return res;
    }
};

 

posted on 2022-10-29 15:49  ᶜʸᵃⁿ  阅读(11)  评论(0编辑  收藏  举报