前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Leetcode -94.二叉树的中序遍历 -145.二叉树的后序遍历】

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

作者头像
YoungMLet
发布2024-03-01 10:18:01
1000
发布2024-03-01 10:18:01
举报
文章被收录于专栏:C++/Linux

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

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

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

示例 2: 输入:root = [] 输出:[]

示例 3: 输入:root = [1] 输出:[1]

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

  • 100 <= Node.val <= 100

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

代码语言:javascript
复制
		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

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

代码语言:javascript
复制
		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;
		}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-02-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Leetcode -94.二叉树的中序遍历
  • Leetcode -145.二叉树的后序遍历
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档