7

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

 2 years ago
source link: https://blog.51cto.com/u_15488507/5582439
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.
neoserver,ios ssh client

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

精选 原创

97的风 2022-08-16 15:27:18 博主文章分类:面试题 ©著作权

文章标签 二叉树 数据 一维数组 文章分类 Java 编程语言 阅读数236

1.简述:

描述

给你二叉树的根节点 root ,返回它节点值的 前序 遍历。

数据范围:二叉树的节点数量满足  ,二叉树节点的值满足  ,树的各节点的值各不相同

#yyds干货盘点# 面试必刷TOP101:二叉树的前序遍历_一维数组_03
示例1
{1,#,2,3}
[1,2,3]

2.代码实现:

import java.util.*;

/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/

public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型一维数组
*/
public int[] preorderTraversal (TreeNode root) {
// write code here
List<Integer> list = new ArrayList<>();
handTree(root, list);
int[] arr = new int[list.size()];
int i = 0;
for(int v : list){
arr[i++] = v;
}
return arr;
}

private void handTree(TreeNode root, List<Integer> list){
if(root != null){
list.add(root.val);
handTree(root.left, list);
handTree(root.right, list);
}
}
}
  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK