Traversal of binary tree is very import when sloving the binary tree problem.
Today I will try starting to record the traversal way I met in leetcode or somewhere else. Continuing update...
1. LevelOrder Traversal using Queue.
This is a very common traversal case. We use it to record the width of the current level.
Plus: Actually is a bfs search in a graph when you replace the left and right node to adjs of a vertex.
Today I will try starting to record the traversal way I met in leetcode or somewhere else. Continuing update...
1. LevelOrder Traversal using Queue.
This is a very common traversal case. We use it to record the width of the current level.
Plus: Actually is a bfs search in a graph when you replace the left and right node to adjs of a vertex.
public class Example { public List<Integer> levelOrderTraversal(TreeNode root) { if (root == null) return null; List<Integer> result = new ArrayList<>(); Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode tmp = queue.poll(); System.out.println(tmp.val); result.add(tmp.val); if (tmp.left != null) queue.offer(tmp.left); if (tmp.right != null) queue.offer(tmp.right); } } return result; } public class TreeNode { int val; TreeNode left; TreeNode right; } }
Comments
Post a Comment