Leetcode之深度优先搜索(DFS)专题-513. 找树左下角的值(Find Bottom Left Tree Value)

2023-06-15,,

Leetcode之深度优先搜索(DFS)专题-513. 找树左下角的值(Find Bottom Left Tree Value)

深度优先搜索的解题详细介绍,点击


给定一个二叉树,在树的最后一行找到最左边的值。

示例 1:

输入:

    2
/ \
1 3 输出:
1

示例 2:

输入:

        1
/ \
2 3
/ / \
4 5 6
/
7 输出:
7

注意: 您可以假设树(即给定的根节点)不为 NULL。


分析:

给定一个根节点不为NULL的树,求最左下角的节点值(即深度最深的,从左往右数第一个的叶子节点的val值)

AC代码:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<List<Integer>> ans = new ArrayList<>();
public int findBottomLeftValue(TreeNode root) {
dfs(root,0);
return ans.get(ans.size()-1).get(0);
}
public void dfs(TreeNode node,int depth){
if(node==null) return; if(ans.size()==depth){
ans.add(new ArrayList<Integer>());
} ans.get(depth).add(node.val);
dfs(node.left,depth+1);
dfs(node.right,depth+1);
}
}

Leetcode之深度优先搜索(DFS)专题-513. 找树左下角的值(Find Bottom Left Tree Value)的相关教程结束。

《Leetcode之深度优先搜索(DFS)专题-513. 找树左下角的值(Find Bottom Left Tree Value).doc》

下载本文的Word格式文档,以方便收藏与打印。