Description,
Given a binary tree, find the leftmost value in the last row of the tree.
Input:
1
/ \
2 3
/ / \
4 5 6
/
7
Output:
7
Note: You may assume the tree (i.e., the given root node) is not NULL.
Pre-order DFS
The trick is using a list to track the following info,
List<Integer, Integer> -- <max_level_met, first_qualified_node_value>
Time complexity: O(n)
Runtime: 7ms
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int[] ret = new int[2];
public int findBottomLeftValue(TreeNode root) {
dfs(root, 1);
return ret[1];
}
private void dfs(TreeNode root, int level){
if (root == null) return;
if (level > ret[0] && root.left == null && root.right == null) {
ret[0] = level;
ret[1] = root.val;
return;
}
dfs(root.left, level+1);
dfs(root.right, level+1);
}
}
Runtime: 7ms