题解 | 二叉树的前序遍历
二叉树的前序遍历
https://www.nowcoder.com/practice/5e2135f4d2b14eb8a5b06fab4c938635
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) {
List<Integer> result=new ArrayList<Integer>();
preorder(root,result);
int[] array = result.stream()
.mapToInt(Integer::intValue) // 或者 .mapToInt(i -> i)
.toArray();
return array;
}
// 子问题 有
public void preorder(TreeNode root,List<Integer> result){
if(root==null){
return;
}
result.add(root.val);// 回溯问题 主要在节点 尾部回溯可以拿到前面的左递归的值和右递归的值 需要注意这个细节
preorder(root.left,result);
preorder(root.right,result);
}
}
查看6道真题和解析