[Golang][Leetcode][BinaryTree]刷題系列-513-Find Bottom Left Tree Value

Contents
513. Find Bottom Left Tree Value
Level : Medium
原題連結 : Click
題目 :
Given the root of a binary tree, return the leftmost value in the last row of the tree.
Example :
Note
Example 1:
Input: root = [2,1,3] Output: 1
Example 2:
Input: root = [1,2,3,4,null,5,6,null,null,7] Output: 7
解題思路 :
- 這題需要你找到最後一排leave中最左邊的那個node的value
- 首先既然要找leave就必須使用dfs去把每一個leave visit一遍,並同時記錄該leave的level當遇到比當前紀錄的leave有更大的level時,替換掉他
- 這時候有些朋友可能會問那怎麼知道他是不是最左邊呢,這時候就可以用兩個小地方去控管
- 這題的寫法需要將visit left node的recursive code寫在visit right node的前面,這樣就能確保他是從左邊開始visit到右邊
- 因為是從左邊visit到右邊,所以我們需要當 maxLevel < curLevel 而不是 maxLevel <= curLevel時做替換,因為先visit的node必定比後進來的node還要左邊
Recursive解法
- time complexity: O(n) , space complexity: O(1)
Runtime: 4 ms, faster than 96.55% of Go online submissions for Find Bottom Left Tree Value.
|
|
最後祝福努力認真的各位 “All your dream of are hidden in your daily life” 我們峰頂見!!!