Given the root of a binary tree, return the inorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,3,2]
Explanation:
Example 2:
Input: root = [1,2,3,4,5,null,8,null,null,6,7,9]
Output: [4,2,6,5,7,1,3,9,8]
Explanation:
Example 3:
Input: root = []
Output: []
Example 4:
Input: root = [1]
Output: [1]
Constraints:
The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100
My Solution
To solve this problem, we can create a helper function to do the inorder traversal and just pass our output list as an argument. We traverse the left node first, then add the current node’s value to the output list, then we can traverse the right node. In this way, we only visit every node once and the time complexity would be O(n). Space complexity would be O(n) for the output list.
/**
* 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> out = new ArrayList<>();
helper(root, out);
return out;
}
public void helper(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
helper(root.left, list);
list.add(root.val);
helper(root.right, list);
}
}