【Leetcode -94.二叉树的中序遍历 -145.二叉树的后序遍历】

简介: 【Leetcode -94.二叉树的中序遍历 -145.二叉树的后序遍历】

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

题目:给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。

示例 1:

输入:root = [1, null, 2, 3]

输出:[1, 3, 2]

示例 2:

输入:root = []

输出:[]

示例 3:

输入:root = [1]

输出:[1]

提示:

树中节点数目在范围[0, 100] 内

  • 100 <= Node.val <= 100

思路:二叉树的中序遍历,化为子问题先遍历当前根的左子树,再打印当前根的值,最后遍历当前根的右子树;

void Inorder(struct TreeNode* root, int* a, int* pos)
    {
        if (root == NULL)
            return;
        //先递归当前根的左子树;再将当前根的 val 存放到数组中;最后递归当前根的右子树
        Inorder(root->left, a, pos);
        a[(*pos)++] = root->val;
        Inorder(root->right, a, pos);
    }
    int* inorderTraversal(struct TreeNode* root, int* returnSize)
    {
        //开辟一个返回中序遍历的数组,pos记录数组的长度
        int* ret = (int*)malloc(sizeof(int) * 100);
        int pos = 0;
        //进入中序遍历
        Inorder(root, ret, &pos);
        *returnSize = pos;
        return ret;
    }

Leetcode -145.二叉树的后序遍历

题目:给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。

示例 1:

输入:root = [1, null, 2, 3]

输出:[3, 2, 1]

示例 2:

输入:root = []

输出:[]

示例 3:

输入:root = [1]

输出:[1]

提示:

树中节点的数目在范围[0, 100] 内

  • 100 <= Node.val <= 100

思路:二叉树的后序遍历,化为子问题先遍历当前根的左子树,再遍历当前根的右子树,最后打印当前根的值;

void Postorder(struct TreeNode* root, int* a, int* pos)
    {
        if (root == NULL)
            return;
        //先递归当前根的左子树;再递归当前根的右子树;最后将当前根的 val 存放到数组中
        Postorder(root->left, a, pos);
        Postorder(root->right, a, pos);
        a[(*pos)++] = root->val;
    }
    int* postorderTraversal(struct TreeNode* root, int* returnSize)
    {
        //开辟返回的数组
        int* ret = (int*)malloc(sizeof(int) * 100);
        int pos = 0;
        //进入后序遍历
        Postorder(root, ret, &pos);
        *returnSize = pos;
        return ret;
    }
目录
相关文章
|
2天前
leetcode代码记录(二叉树的所有路径
leetcode代码记录(二叉树的所有路径
7 0
|
3天前
leetcode代码记录(对称二叉树 中序遍历+回文串 为什么不行
leetcode代码记录(对称二叉树 中序遍历+回文串 为什么不行
6 0
|
3天前
leetcode代码记录(二叉树的最小深度
leetcode代码记录(二叉树的最小深度
7 0
|
3天前
leetcode代码记录(二叉树的最大深度
leetcode代码记录(二叉树的最大深度
5 0
|
3天前
leetcode代码记录(翻转二叉树
leetcode代码记录(翻转二叉树
4 0
|
3天前
leetcode代码记录(二叉树的层序遍历
leetcode代码记录(二叉树的层序遍历
5 0
|
3天前
|
算法
leetcode代码记录(二叉树递归遍历
leetcode代码记录(二叉树递归遍历
6 0
|
16天前
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
|
24天前
|
算法 API DataX
二叉树(下)+Leetcode每日一题——“数据结构与算法”“对称二叉树”“另一棵树的子树”“二叉树的前中后序遍历”
二叉树(下)+Leetcode每日一题——“数据结构与算法”“对称二叉树”“另一棵树的子树”“二叉树的前中后序遍历”
|
2天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
6 0

热门文章

最新文章