嗯。。不会写,看到了两种思路:

思路一:

用DFS的方式递归来往下找,同时记录当前找到的节点所在的深度,他用了一个int数组res,数组第一个元素记录节点值,第二个元素记录节点所在的深度。只有在进入更深一层,且这一层还没有记录节点值时,才记录下找到的第一个节点值,其实也就是最左边的节点值,找到后就将深度标记为当前深度,那么后面找到的所有这个深度的节点值都不再记录,除非又找到了更深的节点。这样一直往下,不断根据深度来更新找到的节点值,最后找到的就是最深一层的最左边的节点值了。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int findBottomLeftValue(TreeNode root) {
        return findLeft( root , 1 , new int[]{0,0} );
    }
    
    public int findLeft( TreeNode root , int depth , int[] res){
        if( res[ 1 ] < depth ){
            res[ 0 ] = root.val;
            res[ 1 ] = depth;

        }
        if( root.left != null )findLeft( root.left , depth + 1 , res );
        if( root.right != null )findLeft( root.right , depth + 1 , res );
        return res[ 0 ];
    }
}

思路二:

513. Find Bottom Left Tree Value

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int findBottomLeftValue(TreeNode root) {
        
        Queue<TreeNode> tree = new LinkedList<>();
        
        tree.add( root );
        
        while( !tree.isEmpty() ){
            root = tree.poll();
            if( root.right != null )tree.add( root.right );
            if( root.left != null )tree.add( root.left );
        }
        return root.val;
    }
}

相关文章:

  • 2021-11-10
  • 2022-12-23
  • 2021-05-15
  • 2022-12-23
  • 2021-09-15
  • 2021-09-30
  • 2021-09-14
  • 2021-11-23
猜你喜欢
  • 2021-05-19
  • 2022-12-23
  • 2022-12-23
  • 2021-10-28
  • 2022-01-31
  • 2022-03-08
相关资源
相似解决方案