Here are 2 of my accepted solution approaches (both O(n) where n is the number of nodes in the input tree) for solving the Problem #94 Binary Tree Inorder Traversal on Leetcode:
Approach 1: Simple Recursive
/** * 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 { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> values = new ArrayList<>(); preorderTraversalRecur(root, values); return values; } void preorderTraversalRecur(TreeNode root, List<Integer> values) { if (root == null) return; values.add(root.val); preorderTraversalRecur(root.left, values); preorderTraversalRecur(root.right, values); } }
Approach 2: Iterative Stack based
/** * 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 { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> values = new ArrayList<>(); inorderTraversal(root, values); return values; } void inorderTraversal(TreeNode root, List<Integer> values) { if (root == null) return; inorderTraversal(root.left, values); values.add(root.val); inorderTraversal(root.right, values); } }
Know of any more alternative? ..Feel free to share your code or suggestions in comments below!
No comments:
Post a Comment