(1)方法一:递归
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型ArrayList
*/
ArrayList<Integer> list = new ArrayList<>();
public ArrayList<Integer> preorderTraversal (TreeNode root) {
if(root!=null){
list.add(root.val); //根节点
preorderTraversal(root.left); //左子树
preorderTraversal(root.right); //右子树
}
return list;
}
}
(2)方法二:非递归
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型ArrayList
思路:非递归。借助栈来实现
*/
int MAXSIZE=100;
ArrayList<Integer> list = new ArrayList<>();
TreeNode s[] = new TreeNode[MAXSIZE];
int top=-1;
public ArrayList<Integer> preorderTraversal (TreeNode root) {
if(root==null){
return list;
}
//每次结点进栈时访问
s[++top] = root;
while(top!=-1){
TreeNode p = s[top--];//出栈栈顶元素
list.add(p.val);
if(p.right!=null){
s[++top] = p.right;
}
if(p.left!=null){
s[++top] = p.left;
}
}//while
return list;
}
}