728x90
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
if (root == null) {
return result;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.isEmpty()){
TreeNode node = stack.pop();
result.add(node.val);
if (node.right != null){
stack.push(node.right);
}
if (node.left != null){
stack.push(node.left);
}
}
return result;
}
}
Preorder Traversal은
Visit, Left, Right의 순서로 기억하면 된다.
728x90
'알고리즘' 카테고리의 다른 글
[LeetCode] 501. Find Mode in Binary Search Tree (0) | 2023.12.06 |
---|---|
[LeetCode] 145. Binary Tree Postorder Traversal (0) | 2023.12.06 |
[LeetCode] 94. Binary Tree Inorder Traversal (0) | 2023.12.05 |
[LeetCode] 111. Minimum Depth of Binary Tree (0) | 2023.12.05 |
[LeetCode] 110. Balanced Binary Tree (0) | 2023.12.05 |