0513. Find Bottom Left Tree Value

513. Find Bottom Left Tree Value #

Problem #

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.

Problem Summary #

Given a binary tree, find the leftmost value in the last row of the tree. Note: You may assume the tree (i.e., the given root node) is not NULL.

Solution Approach #

  • Given a tree, output the value of the leftmost node in the bottommost level of the tree.
  • This problem can be solved using either DFS or BFS.

Code #


package leetcode

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

// Solution 1 DFS
func findBottomLeftValue(root *TreeNode) int {
	if root == nil {
		return 0
	}
	res, maxHeight := 0, -1
	findBottomLeftValueDFS(root, 0, &res, &maxHeight)
	return res
}

func findBottomLeftValueDFS(root *TreeNode, curHeight int, res, maxHeight *int) {
	if curHeight > *maxHeight && root.Left == nil && root.Right == nil {
		*maxHeight = curHeight
		*res = root.Val
	}
	if root.Left != nil {
		findBottomLeftValueDFS(root.Left, curHeight+1, res, maxHeight)
	}
	if root.Right != nil {
		findBottomLeftValueDFS(root.Right, curHeight+1, res, maxHeight)
	}
}

// Solution 2 BFS
func findBottomLeftValue1(root *TreeNode) int {
	queue := []*TreeNode{root}
	for len(queue) > 0 {
		next := []*TreeNode{}
		for _, node := range queue {
			if node.Left != nil {
				next = append(next, node.Left)
			}
			if node.Right != nil {
				next = append(next, node.Right)
			}
		}
		if len(next) == 0 {
			return queue[0].Val
		}
		queue = next
	}
	return 0
}


Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文