给你二叉树的根节点 root
,返回它节点值的 前序 遍历。
输入:root = [1,null,2,3]
输出:[1,2,3]
递归,使用辅助函数
class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<Integer>(); preorder(root, res); return res; } public void preorder(TreeNode root, List<Integer> res) { if (root == null) return; res.add(root.val); preorder(root.left, res); preorder(root.right, res); } }
递归,不使用辅助函数
class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<Integer>(); if (root == null) return res; res.add(root.val); res.addAll(preorderTraversal(root.left)); res.addAll(preorderTraversal(root.right)); return res; } }
迭代
class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<Integer>(); if (root == null) return res; Deque<TreeNode> stack = new LinkedList<TreeNode>(); while (root != null || !stack.isEmpty()) { while (root != null) { res.add(root.val); stack.push(root); root = root.left; } root = stack.pop(); root = root.right; } return res; } }
知识点:无
总结:无