풀이 코드
import java.util.ArrayList;
import java.util.List;
public class LeetCode_0094_BinaryTreeInorderTraversal {
private List<Integer> result = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode94 root) {
if (root == null) {
return result;
}
recursiveInorderTraversal(root);
return result;
}
private void recursiveInorderTraversal(TreeNode94 node) {
if (node.left != null) {
recursiveInorderTraversal(node.left);
}
result.add(node.val);
if (node.right != null) {
recursiveInorderTraversal(node.right);
}
}
}
class TreeNode94 {
int val;
TreeNode94 left;
TreeNode94 right;
TreeNode94() {}
TreeNode94(int val) { this.val = val; }
TreeNode94(int val, TreeNode94 left, TreeNode94 right) {
this.val = val;
this.left = left;
this.right = right;
}
}
테스트코드
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
public class LeetCode_0094_BinaryTreeInorderTraversalTest {
@Test
public void inorderTraversalTest_1() {
LeetCode_0094_BinaryTreeInorderTraversal test = new LeetCode_0094_BinaryTreeInorderTraversal();
TreeNode94 root = new TreeNode94(1);
TreeNode94 node2 = new TreeNode94(2);
TreeNode94 node3 = new TreeNode94(3);
root.right = node2;
node2.left = node3;
assertThat(test.inorderTraversal(root)).containsExactly(1,3,2);
}
@Test
public void inorderTraversalTest_2() {
LeetCode_0094_BinaryTreeInorderTraversal test = new LeetCode_0094_BinaryTreeInorderTraversal();
TreeNode94 root = new TreeNode94();
assertThat(test.inorderTraversal(root)).containsExactly(0);
}
@Test
public void inorderTraversalTest_3() {
LeetCode_0094_BinaryTreeInorderTraversal test = new LeetCode_0094_BinaryTreeInorderTraversal();
TreeNode94 root = new TreeNode94(1);
assertThat(test.inorderTraversal(root)).containsExactly(1);
}
}
'Algorithm > Leet Code' 카테고리의 다른 글
[LeetCode] 130. Surrounded Regions (BFS, DFS, TDD, 코테, 릿코드, tech interview) (0) | 2022.01.03 |
---|---|
[LeetCode] 202. Happy Number (TDD, 코테, 릿코드, tech interview) (0) | 2021.12.29 |
[LeetCode] 771. Jewels and Stones(코딩테스트, 릿코드, tech interview) (0) | 2021.09.22 |
[LeetCode] 7. Reverse Integer (코딩테스트, 릿코드, tech interview) (0) | 2021.08.26 |
[LeetCode] 1. Two Sum (코딩테스트, 릿코드, tech interview) (0) | 2021.08.25 |