/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/classSolution{
List<Integer> list =newLinkedList<>();public List<Integer>preorderTraversal(TreeNode root){if(root==null)returnnewLinkedList<>();helper(root);return list;}publicvoidhelper(TreeNode root){if(root==null)return;
list.add(root.val);helper(root.left);helper(root.right);return;}}
方法二:迭代
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/classSolution{public List<Integer>preorderTraversal(TreeNode root){
List<Integer> res =newLinkedList<>();if(root==null)return res;
TreeNode cur = root;
Stack<TreeNode> st =newStack<>();while(!st.isEmpty()||cur!=null){while(cur==null&&!st.isEmpty()){
cur = st.pop().right;}if(cur == null)return res;
st.push(cur);
res.add(cur.val);
cur = cur.left;}return res;}}
LeetCode144-二叉树的前序遍历题目解法方法一:递归/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { List<Integer> list =