Leetcode—94.二叉树的中序遍历【简单】

2023每日刷题(四十)

Leetcode—94.二叉树的中序遍历

Leetcode—94.二叉树的中序遍历【简单】_第1张图片

C语言实现代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
void dfs(struct TreeNode* root, int *len, int *arr) {
    if(root != NULL) {
        dfs(root->left, len, arr);
        arr[*len] = root->val;
        (*len)++;
        dfs(root->right, len, arr);
    }
}

int* inorderTraversal(struct TreeNode* root, int* returnSize) {
    *returnSize = 0;
    if(root == NULL) {
        return NULL;
    }
    int *array = (int *)calloc(103, sizeof(int));
    dfs(root, returnSize, array);
    
    return array;
}

运行结果

Leetcode—94.二叉树的中序遍历【简单】_第2张图片

C++递归实现代码

/**
 * 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> ans;
    void inorder(TreeNode* root) {
        if(root != nullptr) {
            inorder(root->left);
            ans.push_back(root->val);
            inorder(root->right);
        }
    }
    vector<int> inorderTraversal(TreeNode* root) {
        inorder(root);
        return ans;
    }
};

运行结果

Leetcode—94.二叉树的中序遍历【简单】_第3张图片

C++非递归实现代码

/**
 * 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> ans;
    void inorder(TreeNode* root) {
        if(root == nullptr) {
            return;
        }
        stack<TreeNode*> st;
        TreeNode* p = root;
        while(!st.empty() || p != nullptr) {
            // 扫描p的所有左下结点并进栈
            while(p != nullptr) {
                st.push(p);
                p = p->left;
            }
            if(!st.empty()) {
                p = st.top();
                st.pop();
                ans.push_back(p->val);
                p = p->right;
            }
        }
    }
    vector<int> inorderTraversal(TreeNode* root) {
        inorder(root);
        return ans;
    }
};

运行结果

Leetcode—94.二叉树的中序遍历【简单】_第4张图片
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

你可能感兴趣的:(LeetCode刷题,leetcode,深度优先,算法,经验分享,c语言,c++)