3

#yyds干货盘点# 面试必刷TOP101:二叉树的中序遍历

 1 year ago
source link: https://blog.51cto.com/u_15488507/5587685
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#yyds干货盘点# 面试必刷TOP101:二叉树的中序遍历

精选 原创

97的风 2022-08-17 17:39:42 博主文章分类:面试题 ©著作权

文章标签 子树 中序遍历 代码实现 文章分类 Java 编程语言 阅读数308

1.简述:

描述

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

数据范围:树上节点数满足 ,树上每个节点的值满足 进阶:空间复杂度 ,时间复杂度 

示例1
{1,2,#,#,3}
[2,3,1]
示例2
{1,2}
[2,1]
示例4
{1,#,2}
[1,2]

2.代码实现:

import java.util.*;
public class Solution {
public void inorder(List<Integer> list, TreeNode root){
//遇到空节点则返回
if(root == null)
return;
//先去左子树
inorder(list, root.left);
//再访问根节点
list.add(root.val);
//最后去右子树
inorder(list, root.right);
}

public int[] inorderTraversal (TreeNode root) {
//添加遍历结果的数组
List<Integer> list = new ArrayList();
//递归中序遍历
inorder(list, root);
//返回的结果
int[] res = new int[list.size()];
for(int i = 0; i < list.size(); i++)
res[i] = list.get(i);
return res;
}
}
  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK