给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。
假设二叉树中至少有一个节点。
示例 1:

输入: root = [2,1,3]
输出: 1
示例 2:

输入: [1,2,3,4,null,5,6,null,null,7]
输出: 7
提示:
[1,104]-231 <= Node.val <= 231 - 1注意:本题与主站 513 题相同: https://leetcode-cn.com/problems/find-bottom-left-tree-value/
Related Topics
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/LwUNpT
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
定义两个全局变量,记录高度和当前符合题意的值,深度遍历,当遍历节点高于当前高度时,记录当前值,先dfs左节点,再dfs右节点,这样如果左节点有值,右节点并没有左节点高度高,也不会取到。
class Solution {
int curVal = 0;
int curHeight = 0;
public int findBottomLeftValue(TreeNode root) {
int curHeight = 0;
dfs(root,0);
return curVal;
}
public void dfs(TreeNode root, int height){
if (root == null) return;
height++;
dfs(root.left,height);
dfs(root.right,height);
if (height > curHeight){
curHeight = height;
curVal = root.val;
}
}
}