LeetCode 513. 找树左下角的值Golang版
LeetCode 513. 找树左下角的值Golang版
1. 问题描述
给定一个二叉树,在树的最后一行找到最左边的值。
2. 思路
2.1. 递归
如果需要遍历整颗树,递归函数就不能有返回值。如果需要遍历某⼀条固定路线,递归函数就⼀定要有返回值
2.2. 迭代
层序遍历模板题
3. 代码
3.2. 迭代
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func findBottomLeftValue(root *TreeNode) int { var res int if root == nil { return res } queue := []*TreeNode{ root} for len(queue) > 0 { length := len(queue) for i := 0; i < length; i++ { if queue[0].Left != nil { queue = append(queue, queue[0].Left) } if queue[0].Right != nil { queue = append(queue, queue[0].Right) } if i == 0 { res = queue[0].Val } queue = queue[1:] } } return res }
下一篇:
排序算法---希尔排序(C语言)