1. Preorder
/** * 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<Integer>(); public List<Integer> preorderTraversal(TreeNode root) { preOrder(root); return list; } public void preOrder(TreeNode root) { if(root != null) { list.add(root.val); preOrder(root.left); preOrder(root.right); } } }
2. InOrder
/** * 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<Integer>(); public List<Integer> inorderTraversal(TreeNode root) { inorder(root); return list; } public void inorder(TreeNode root) { if(root != null) { inorder(root.left); list.add(root.val); inorder(root.right); } } }
3. Postorder
/** * 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<Integer>(); public List<Integer> postorderTraversal(TreeNode root) { postorder(root); return list; } public void postorder(TreeNode root) { if(root != null) { postorder(root.left); postorder(root.right); list.add(root.val); } } }
'JAVA > leetcode' 카테고리의 다른 글
[LeetCode] Maximum Depth of Binary Tree (0) | 2021.08.11 |
---|---|
[LeetCode] Binary Tree Level Order Traversal - LevelOrder/BFS (0) | 2021.08.11 |
[LeetCode Medium] BST - Delete Node in a BST !! (0) | 2021.08.10 |
[LeetCode Medium] BST - Insert into a Binary Search Tree (0) | 2021.08.10 |
[LeetCoed] BST - Search in a Binary Search Tree (0) | 2021.08.10 |