首页 > 其他 > 详细

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

时间:2019-08-15 14:29:34      阅读:87      评论:0      收藏:0      [点我收藏+]

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)

原文:https://www.cnblogs.com/qinyuguan/p/11357587.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!