[자료구조] Binary Tree Level Order Traversal
바이너리 트리 레벨선회 구현하기
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { List<List<Integer>> returnList = new ArrayList<List<Integer>>(); ArrayList<TreeNode> queue = new ArrayList<TreeNode>(); int pos = 0; int level = 0; int queueSize = 0; public List<List<Integer>> levelOrder(TreeNode root) { if(root != null){ queue.add(root); } while(pos != queue.size()){ queueSize = queue.size(); List<Integer> levelValueList = new ArrayList<Integer>(); while(pos < queueSize){ TreeNode node = queue.get(pos); if(node.left != null){ queue.add(node.left); } if(node.right != null){ queue.add(node.right); } levelValueList.add(node.val); pos++; } returnList.add(levelValueList); } return returnList; } }
최근 댓글