/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */publicclassSolution{publicList<Integer>preorderTraversal(TreeNoderoot){List<Integer>ret=newLinkedList<Integer>();if(root==null)returnret;Stack<TreeNode>rights=newStack<TreeNode>();while(root!=null){ret.add(root.val);if(root.right!=null)rights.push(root.right);root=root.left;if(root==null&&!rights.isEmpty())root=rights.pop();}returnret;}}