题目链接
https://leetcode.com/problems/find-bottom-left-tree-value/description/
题目描述
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
Note: You may assume the tree (i.e., the given root node) is not NULL.
题解
递归遍历每一个节点,同时记录一下当前的深度,只有深度大于当前最大深度的时候,才更新值,不然节点遍历。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int value = 0;
private int ant = Integer.MIN_VALUE;
public int findBottomLeftValue(TreeNode root) {
findBottomLeftValue(root, 0);
return value;
}
public void findBottomLeftValue(TreeNode root, int level) {
if (root == null) { return ; }
findBottomLeftValue(root.left, level + 1);
findBottomLeftValue(root.right, level + 1);
if (level > ant) {
ant = level;
value = root.val;
}
}
}