# [编程题]二叉树的前序遍历（Java实现）

[编程题]二叉树的前序遍历（Java实现） 题目来源 题目描述

1

2
/
3

leetcode代码

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
ListInteger list=new ArrayList();
public ListInteger preorderTraversal(TreeNode root) {
if(root==null)return list;
preorderTraversal(root.left);
preorderTraversal(root.right);
return list;
}
}
``````

``````import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
static ListInteger list=new ArrayList();
public static void  main(String[] args){
TreeNode root=new TreeNode(1);
root.left=new TreeNode(3);
root.right=new TreeNode(5);
root.left.left=new TreeNode(2);
root.right.left=new TreeNode(4);
preorderTraversal(root);
System.out.println(Arrays.toString(list.toArray()));
}
public static ListInteger preorderTraversal(TreeNode root) {
if(root==null)return list;
preorderTraversal(root.left);
preorderTraversal(root.right);
return list;
}
}
class TreeNode{
int val;
TreeNode(){}
TreeNode (int val){
this.val=val;
}
TreeNode left;
TreeNode right;
}
``````

leetcode代码

``````import java.util.Stack;
/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/

class Solution {
ListInteger list=new ArrayList();
public ListInteger preorderTraversal(TreeNode root) {
if(root==null)return list;
StackTreeNodestack=new Stack();
while(root!=null||!stack.isEmpty()){
while(root!=null){
stack.push(root);
root=root.left;
}
if(!stack.isEmpty()){
root=stack.pop();
root=root.right;
}
}
return list;
}
}
``````

``````import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
public class Main {
static ListInteger list=new ArrayList();
public static void  main(String[] args){
TreeNode root=new TreeNode(1);
root.left=new TreeNode(3);
root.right=new TreeNode(5);
root.left.left=new TreeNode(2);
root.right.left=new TreeNode(4);
preorderTraversal(root);
System.out.println(Arrays.toString(list.toArray()));
}
public static ListInteger preorderTraversal(TreeNode root) {
if(root==null)return list;
StackTreeNode stack=new Stack();
while(root!=null||!stack.isEmpty()){
while(root!=null){
stack.push(root);
root=root.left;
}
if(!stack.isEmpty()){
root=stack.pop();
root=root.right;
}
}
return list;
}
}
class TreeNode{
int val;
TreeNode(){}
TreeNode (int val){
this.val=val;
}
TreeNode left;
TreeNode right;
}
``````
• 王者荣耀