Table of contents
144. Preorder traversal of binary trees - LeetCode
Example 1:
Input: root = [1,null,2,3] Output: [1,2,3]Example 2:
Input: root = [] Output: []Example 3:
Input: root = [1] Output: [1]Example 4:
Input: root = [1,2] Output: [1,2]Example 5:
Input: root = [1,null,2] Output: [1,2]hint:
- The number of nodes in the tree is
[0, 100]
within the range-100 <= Node.val <= 100
Advanced: The recursive algorithm is simple, can you do it with an iterative algorithm?
Code:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { List<Integer> List=new ArrayList<>(); public List<Integer> preorderTraversal(TreeNode root) { fun(root); return List; } public void fun(TreeNode root){ if(root==null) return; List.add(root.val); fun(root.left); fun(root.right); } }
operation result: