🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
![](https://box.kancloud.cn/35020e6c726c7baa130396ad97662ef1_1195x629.png) ~~~ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> ls = new ArrayList<Integer>(); if(root==null) return ls; Stack<TreeNode> st = new Stack<TreeNode>(); //HashSet<TreeNode> hs = new HashSet<TreeNode>(); st.push(root); while(!st.isEmpty()) { TreeNode temp = st.pop(); ls.add(temp.val); if(temp.right!=null) st.push(temp.right); if(temp.left!=null) st.push(temp.left); //} } return ls; } } ~~~