7
#yyds干货盘点# 面试必刷TOP101:二叉树的前序遍历
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.
#yyds干货盘点# 面试必刷TOP101:二叉树的前序遍历
精选 原创1.简述:
描述给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
数据范围:二叉树的节点数量满足 ,二叉树节点的值满足 ,树的各节点的值各不相同
示例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);
}
}
}
/*
* 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);
}
}
}
- 赞
- 收藏
- 评论
- 分享
- 举报
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK