Solution to Binary Tree Level Order Traversal by LeetCode

4 Jul

Question Name: Binary Tree Level Order Traversal

3 Replies to “Solution to Binary Tree Level Order Traversal by LeetCode”

1. Dragon Snake says:

Hi – Well , I m a bit confused with this one particular line of code :
“for father in result[-1]: ”
This looks up only the last element in the result ( and adds its children to the Queue (ie) NextLayer .
What if you have two elements – aren’t you missing the internal element (since you are just looking at the top most element ? )
BTW – just wanted to clarify ; I m pretty sure the OJ accepted this solution and its correct. Just wanted to clarify for my understanding.

• Sheng says:

Sorry for the bad style. Python is dynamic type. Actually the type of result inside while loop is different from the type after while loop.
Inside while loop, the result is a list of list of nodes like: [[first node in first layer, second node in second layer], [first node in second layer, … …], [], …]
After the while loop, we change the type of result:
result = [[node.val for node in layer] for layer in result]
Then it is a list of nodes, such as [first node in first layer, second node in second layer, first node in second layer, …]

2. micropentium6 says: