Given a binary tree, find the leftmost value in the last row of the tree.
Example 1:
Input:
Output:
1
Example 2:
Input:
Output:
7
Note: You may assume the tree (i.e., the given root node) is not NULL.
解法1:DFS, O(N)
这题code写起来很简单,思路是这样的:每到一层第一个扫描到的可能就是我们要找的node。那么不断的更新这个node的值最后当遍历完这个树之后就可以得到答案了。
DFS遍历的时候维护一个全局变量maxdepth, 然后每下一层就更新一下当前的depth,如果depth比maxdepth大,说明当前到达的是一个新层,而且访问的一定是这一层的最左的元素。
Java