Given a binary tree, find the leftmost value in the last row of the tree.
Example 1:
Input:
2
/ \
1 3
Output:
1
Example 2:
Input:
1
/ \
2 3
/ / \
4 5 6
/
7
Output:
7
析:开始自己写的是判断数的深度,如果左子树深度大于右子树,就走左否则走右。但是时间超时。
解法:每次把一行的数据保存下来,找第一个即可
用List存储一行。
public int findBottomLeftValue(TreeNode root) {
int res = root.val;
// list1存放树中当前行的数据
List<TreeNode> list1 = new ArrayList<>();
List<TreeNode> list2 = new ArrayList<>();
list1.add(root);
while(!list1.isEmpty()){
res = list1.get(0).val;
list2.clear();
for(int i=0;i<list1.size();i++){
if(list1.get(i).left!=null)
list2.add(list1.get(i).left);
if(list1.get(i).right!=null)
list2.add(list1.get(i).right);
}
list1.clear();
list1.addAll(list2);
}
return res;
}