題目描述
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
解題思路
就一句話(huà):從右到左的層次遍歷
基礎(chǔ)是層次遍歷漠另,但是基礎(chǔ)層次遍歷是 根出隊(duì)红且,左入隊(duì),右入隊(duì)打颤。
這樣我們的隊(duì)列最后一個(gè)出隊(duì)的 一定是一個(gè)葉子結(jié)點(diǎn)籽懦,而且是 葉子結(jié)點(diǎn)的 最右一個(gè)于个,
那么我們要求 最底下最左的 葉子結(jié)點(diǎn),那么只需要入隊(duì)順序更改一下暮顺。
題解
public int findBottomLeftValue(TreeNode root) {
// 這里隊(duì)列的 初始化 是 LinkedList
Queue<TreeNode> queue = new LinkedList<>();
// 入隊(duì) offer 出隊(duì) poll
queue.offer(root);
TreeNode node = root;
while(!queue.isEmpty()){
node = queue.poll();
if (node.right != null){
queue.offer(node.right);
}
if (node.left != null){
queue.offer(node.left);
}
}
return node.val;
}