Files
LeetCode-Go/website/content/ChapterFour/0513.Find-Bottom-Left-Tree-Value.md
2020-08-09 00:39:24 +08:00

112 lines
1.9 KiB
Markdown
Executable File
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [513. Find Bottom Left Tree Value](https://leetcode.com/problems/find-bottom-left-tree-value/)
## 题目
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**.
## 题目大意
给定一个二叉树,在树的最后一行找到最左边的值。注意: 您可以假设树(即给定的根节点)不为 NULL。
## 解题思路
- 给出一棵树,输出这棵树最下一层中最左边的节点的值。
- 这一题用 DFS 和 BFS 均可解题。
## 代码
```go
package leetcode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// 解法一 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)
}
}
// 解法二 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
}
```