반응형
leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
문제
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
return its zigzag level order traversal as:
접근
큐보다 스택을 이용해서 접근함
코드
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class LC103_BinaryTreeZigZagTraversal {
public static void main(String[] args) {
}
// 레벨 별 스택 사용
// 플래그 변수 사용 -> 탐색방향을 결정
public static List<List<Integer>> solution(TreeNode root) {
List<List<Integer>> ret = new ArrayList<>();
if(root==null) return ret;
boolean flag = true;
Stack<TreeNode> s = new Stack<>();
s.push(root);
while(!s.isEmpty()) {
int size = s.size();
Stack<TreeNode> newStack = new Stack<>();
List<Integer> level = new ArrayList<>();
for(int i=0; i<size; i++) {
// 현재 레벨 노드들, 그 자손들 처리
TreeNode node = s.pop();
level.add(node.val);
if(flag) {
if(node.left!=null) newStack.push(node.left);
if(node.right!=null) newStack.push(node.right);
}else {
if(node.right!=null) newStack.push(node.right);
if(node.left!=null) newStack.push(node.left);
}
}
ret.add(level);
s = newStack;
flag = !flag;
}
return ret;
}
public class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x){
val = x;
}
}
}
반응형
'알고리즘 > [ LeetCode ]' 카테고리의 다른 글
[ LeetCode ][JAVA][3] Longest Substring Without Repeating Characters (0) | 2021.11.12 |
---|---|
[ LeetCode ][JAVA][146] LRU Cache (0) | 2021.05.11 |
[ LeetCode ][JAVA][36] Valid Sudoku(스도쿠 판별) (3) | 2020.09.24 |
[ LeetCode ][JAVA][37] Sudoku Solver (스도쿠 풀기) (0) | 2020.09.24 |
[ LeetCode ][JAVA][169] Majority Element (과반수알고리즘) (2) | 2020.09.24 |