[LeetCode 94] Binary Tree Inorder Traversal
LeetCode 94 (Java)
[Binary Tree Inorder Traversal] 문제 풀이
[LeetCode 94] Binary Tree Inorder Traversal
Description
Given the root of a binary tree, return the inorder traversal of its nodes’ values.
Example 1
Example 2
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
Code
내 제출
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* 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 {
private List<Integer> ans = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
dfs(root);
return ans;
}
private void dfs(TreeNode root) {
if (root == null) {
return;
}
dfs(root.left);
ans.add(root.val);
dfs(root.right);
}
}
| Runtime | Memory |
|---|---|
| 0 ms | 41.7 MB |
다른 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
inorder(root, res);
return res;
}
private void inorder(TreeNode root, List<Integer> res) {
if (root == null) return; // base case
inorder(root.left, res); // go LEFT
res.add(root.val); // visit ROOT
inorder(root.right, res); // go RIGHT
}
}
Reference
- https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/Solution.java
This post is licensed under CC BY 4.0 by the author.


