https://leetcode.com/problems/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).
https://discuss.leetcode.com/topic/7332/java-solution-using-dfs
http://leetcode.com/2010/09/printing-binary-tree-in-level-order.html
Recursive Version
http://blog.hfknight.com/?p=1249
DFS
public void levelOrderHelper(TreeNode tn, List<List<Integer>> result, int depth) { if (tn == null) return; List<Integer> tempSet; if (result.size() < depth) { // add new set tempSet = new ArrayList<Integer>(); result.add(tempSet); } else { tempSet = result.get(depth-1); } tempSet.add(tn.val); levelOrderHelper(tn.left, result, depth+1); levelOrderHelper(tn.right, result, depth+1); }
Read full article from LeetCode - Binary Tree Level Order Traversal | Darren's Blog
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
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] ]X. https://discuss.leetcode.com/topic/7647/java-solution-with-a-queue-used
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
List<List<Integer>> wrapList = new LinkedList<List<Integer>>();
if(root == null) return wrapList;
queue.offer(root);
while(!queue.isEmpty()){
int levelNum = queue.size();
List<Integer> subList = new LinkedList<Integer>();
for(int i=0; i<levelNum; i++) {
if(queue.peek().left != null) queue.offer(queue.peek().left);
if(queue.peek().right != null) queue.offer(queue.peek().right);
subList.add(queue.poll().val);
}
wrapList.add(subList);
}
return wrapList;
}
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
List<Integer> level = new ArrayList<>();
int cnt = queue.size();
for (int i = 0; i < cnt; i++) {
TreeNode node = queue.poll();
level.add(node.val);
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
res.add(level);
}
return res;
X. DFShttps://discuss.leetcode.com/topic/7332/java-solution-using-dfs
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
levelHelper(res, root, 0);
return res;
}
public void levelHelper(List<List<Integer>> res, TreeNode root, int height) {
if (root == null) return;
if (height >= res.size()) {
res.add(new LinkedList<Integer>());
}
res.get(height).add(root.val);
levelHelper(res, root.left, height+1);
levelHelper(res, root.right, height+1);
}
http://leetcode.com/2010/09/printing-binary-tree-in-level-order.html
In order to print the binary tree in level order with newline in the end of each level, we can utilize two queues. The first queue stores the current level’s nodes, while the second queue stores the next level’s nodes (the current level nodes’ children).
When the first queue is emptied, we know that it must have reached the end of the current level, therefore we print a newline. Then, we switch the emptied first queue with the second queue (which is populated with the next level’s nodes). Then we repeat the process over again.
void printLevelOrder(BinaryTree *root) {
if (!root) return;
queue<BinaryTree*> currentLevel, nextLevel;
currentLevel.push(root);
while (!currentLevel.empty()) {
BinaryTree *currNode = currentLevel.front();
currentLevel.pop();
if (currNode) {
cout << currNode->data << " ";
nextLevel.push(currNode->left);
nextLevel.push(currNode->right);
}
if (currentLevel.empty()) {
cout << endl;
swap(currentLevel, nextLevel);
}
}
}
Is it possible that a solution exists using only one single queue? Yes, you bet. The single queue solution requires two extra counting variables which keep tracks of the number of nodes in the current level (nodesInCurrentLevel) and the next level (nodesInNextLevel). When we pop a node off the queue, we decrement nodesInCurrentLevel by one. When we push its child nodes to the queue, we increment nodesInNextLevel by two. When nodesInCurrentLevel reaches 0, we know that the current level has ended, therefore we print an endline here.
void printLevelOrder(BinaryTree *root) {
if (!root) return;
queue<BinaryTree*> nodesQueue;
int nodesInCurrentLevel = 1;
int nodesInNextLevel = 0;
nodesQueue.push(root);
while (!nodesQueue.empty()) {
BinaryTree *currNode = nodesQueue.front();
nodesQueue.pop();
nodesInCurrentLevel--;
if (currNode) {
cout << currNode->data << " ";
nodesQueue.push(currNode->left);
nodesQueue.push(currNode->right);
nodesInNextLevel += 2;
}
if (nodesInCurrentLevel == 0) {
cout << endl;
nodesInCurrentLevel = nodesInNextLevel;
nodesInNextLevel = 0;
}
}
}
For space efficiency, we can use two variables to keep track of the number of remaining nodes in the current level, and the number of nodes in the next level.
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (root == null)
return result;
// Used as a queue to save children nodes explored in the next level
Deque<TreeNode> nodesInALevel = new ArrayDeque<TreeNode>();
nodesInALevel.add(root);
// Values in the current level
ArrayList<Integer> valuesInCurrentLevel = new ArrayList<Integer>();
// remaining: number of remaining nodes in the current level;
// newlyAdded: number of nodes for the next level
int remaining = 1, newlyAdded = 0;
while(remaining != 0) {
TreeNode currentNode = nodesInALevel.poll();
valuesInCurrentLevel.add(currentNode.val);
remaining--;
if (currentNode.left != null) { // Save its left child (if any) to be explored in the next level
nodesInALevel.add(currentNode.left);
newlyAdded++;
}
if (currentNode.right != null) { // Save its right child (if any) to be explored in the next level
nodesInALevel.add(currentNode.right);
newlyAdded++;
}
if (remaining == 0) { // Current level is done; get ready for the next level
remaining = newlyAdded;
newlyAdded = 0;
result.add(valuesInCurrentLevel);
valuesInCurrentLevel = new ArrayList<Integer>();
}
}
return result;
}
Alternative solution, Use Queue: http://codercareer.blogspot.com/2011/10/no-11-print-binary-trees-from-top-to.html
void PrintFromTopToBottom(BinaryTreeNode* pTreeRoot)
{
if(!pTreeRoot)
return;
std::deque<BinaryTreeNode *> dequeTreeNode;
dequeTreeNode.push_back(pTreeRoot);
while(dequeTreeNode.size())
{
BinaryTreeNode *pNode = dequeTreeNode.front();
dequeTreeNode.pop_front();
printf("%d ", pNode->m_nValue);
if(pNode->m_pLeft)
dequeTreeNode.push_back(pNode->m_pLeft);
if(pNode->m_pRight)
dequeTreeNode.push_back(pNode->m_pRight);
}
}Recursive Version
http://blog.hfknight.com/?p=1249
DFS
public void levelOrderHelper(TreeNode tn, List<List<Integer>> result, int depth) { if (tn == null) return; List<Integer> tempSet; if (result.size() < depth) { // add new set tempSet = new ArrayList<Integer>(); result.add(tempSet); } else { tempSet = result.get(depth-1); } tempSet.add(tn.val); levelOrderHelper(tn.left, result, depth+1); levelOrderHelper(tn.right, result, depth+1); }
Read full article from LeetCode - Binary Tree Level Order Traversal | Darren's Blog