给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,2,3]
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<Integer> preorderTraversal(TreeNode root) { Stack<TreeNode> stack = new Stack<>(); TreeNode p = root; List<Integer> res = new ArrayList<>(); while(p!=null || !stack.empty()){ if(p==null){ p = stack.pop(); } res.add(p.val); if(p.right!=null){ stack.push(p.right); } p = p.left; } return res; } }