题解 | #二叉树的前序遍历#
二叉树的前序遍历
https://www.nowcoder.com/practice/5e2135f4d2b14eb8a5b06fab4c938635
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型一维数组 */ public int[] preorderTraversal (TreeNode root) { // write code here Stack<TreeNode> s=new Stack<>(); ArrayList<Integer> list=new ArrayList<>(); int [] l=new int[0]; if(root==null){ return l; } s.push(root); while(!s.isEmpty()){ if(root.left!=null){//2,1 先要打印顶点在判断是子数个数,2个,指向左子数,将右子数入栈。 list.add(root.val); if(root.right!=null) s.push(root.right); root=root.left; }else{//1,0 if(root.right!=null){//打印顶点,指向右子数 list.add(root.val); root=root.right; }else{//出栈,存入的是右子数不用堵端口 list.add(root.val); root=s.pop(); } } }l=new int[list.size()]; for(int i=0;i<l.length;i++){ l[i]=list.get(i); } return l; } }