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
Solution1:DFS
思路:
Time Complexity: O(N) Space Complexity: O(N)
Solution2:BFS
思路:
Time Complexity: O(N) Space Complexity: O(N)
Solution1a Code:
public class Solution {
int ans=0, h=0;
public int findBottomLeftValue(TreeNode root) {
findBottomLeftValue(root, 1);
return ans;
}
public void findBottomLeftValue(TreeNode root, int depth) {
if (h<depth) {ans=root.val;h=depth;}
if (root.left!=null) findBottomLeftValue(root.left, depth+1);
if (root.right!=null) findBottomLeftValue(root.right, depth+1);
}
}
Solution1b Code:
No global variables, 6ms (faster):
public class Solution {
public int findBottomLeftValue(TreeNode root) {
return findBottomLeftValue(root, 1, new int[]{0,0});
}
public int findBottomLeftValue(TreeNode root, int depth, int[] res) {
if (res[1]<depth) {res[0]=root.val;res[1]=depth;}
if (root.left!=null) findBottomLeftValue(root.left, depth+1, res);
if (root.right!=null) findBottomLeftValue(root.right, depth+1, res);
return res[0];
}
}
Solution2 Code:
class Solution {
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
root = queue.poll();
if (root.right != null)
queue.add(root.right);
if (root.left != null)
queue.add(root.left);
}
return root.val;
}
}