思路:
1.简单的前序遍历 ,根 左右
2.利用栈实现BFS,或者递归
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
if(root == null ){
return new int[]{};
}
//根左右
ArrayList<Integer> result = new ArrayList<>();
preOrderBFS(root, result);
return result.stream().mapToInt(Integer::intValue).toArray();
}
private void preOrder(TreeNode node ,ArrayList<Integer> result){
if(node == null){
return;
}
result.add(node.val);
preOrder(node.left, result);
preOrder(node.right, result);
}
private void preOrderBFS(TreeNode node ,ArrayList<Integer> result){
if(node == null){
return;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(node);
while(!stack.empty()){
TreeNode temp = stack.pop();
result.add(temp.val);
if(temp.right != null){
stack.push(temp.right);
}
if(temp.left != null){
stack.push(temp.left);
}
}
}
}