Last updated 4 years ago
Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Follow up: Recursive solution is trivial, could you do it iteratively?
Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,3,2]
/** * 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> inorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<>(); Stack<TreeNode> stack = new Stack<>(); while(root != null || !stack.isEmpty()) { while (root != null) { stack.push(root); root = root.left; } root = stack.pop(); list.add(root.val); root = root.right; } return list; } }