递归
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<Integer> preorderTraversal(TreeNode root) { // 递归三要素 List<Integer> result = new ArrayList<>(); preoder(root,result); return result; } // 1.入参,返回值 void preoder(TreeNode root,List<Integer> result){ // 2.出栈条件 if(root == null){ return; } // 前序遍历,中--左--右 // 3.单层执行递归逻辑 result.add(root.val); preoder(root.left,result); preoder(root.right,result); } } 迭代 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<Integer> preorderTraversal(TreeNode root) { // 迭代 List<Integer> result = new ArrayList<>(); Stack<TreeNode> stack = new Stack<TreeNode>(); while(stack.size()>0 || root != null){ if(root!=null){ result.add(root.val); stack.push(root); root = root.left; }else{ TreeNode temp = stack.pop(); root = temp.right; } } return result; } } 标签:144,right,TreeNode,val,前序,二叉树,left,root,result From: https://www.cnblogs.com/JavaYuYin/p/18013947