给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [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<>(); List<Integer> list = new ArrayList<>(); if(root == null) return list; stack.push(root); while(!stack.isEmpty()){ root = stack.pop(); list.add(root.val); if(root.right != null){ stack.push(root.right); } if(root.left != null){ stack.push(root.left); } } return list; } }