In: Computer Science
Code using JAVA:
must include "Main Method" for IDE testing!
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x),
left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
}
};
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]
Example 2:
Input: root = [] Output: []
Example 3:
Input: root = [1] Output: [1]
Example 4:
Input: root = [1,2] Output: [2,1]
Example 5:
Input: root = [1,null,2] Output: [1,2]
Constraints:
The code is tested and should run as a single file in any IDE. The main method is also included. An output is also attached. The idea of inorder traversal is simple:
Helpful and self-explanatory comments are added to the code.
Code
import java.util.*;
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;
}
}
public class Solution {
public static void rec(TreeNode root, List <Integer> result) {
if (root == null) {
// If root is null, just return
return;
}
// Visit left subtree
rec(root.left, result);
// Visit root
result.add(root.val);
// Visit right subtree
rec(root.right, result);
}
public static List<Integer> inorderTraversal(TreeNode root) {
// Array to store the result
List<Integer> result = new ArrayList<Integer> ();
// Call recursive inorder traversal function
rec(root, result);
// Return result
return result;
}
public static void main(String []args) {
/*
1
2 5
3 4 6 7
inorder - [3, 2, 4, 1, 6, 5, 7]
*/
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(4);
root.right = new TreeNode(5);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(7);
List<Integer> result = inorderTraversal(root);
System.out.print("Inorder: ");
for (int i = 0; i < result.size(); i++) {
System.out.print(result.get(i) + " ");
}
}
}
Output