前序遍历:根左右
import java.util.Stack;
import java.util.ArrayList;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> list=new ArrayList<>();
Stack<TreeNode> stack =new Stack<>();
if(root==null){
return list;
}
stack.push(root);//根
while(!stack.isEmpty()){
TreeNode temp =stack.pop();//记录栈顶元素
list.add(temp.val);
if(temp.right!=null){ //入右
stack.push(temp.right);
}
if(temp.left!=null){ //入左
stack.push(temp.left);
}
}
return list;
}
}