今日中等题:https://leetcode.cn/problems/find-bottom-left-tree-value/
终于走出舒适区开始做树相关的题目了,开始因为对概念不熟悉看完题目是懵逼的,但是再看题解的深度优先和广度优先的算法后,突然发现不过如此hhhh,用双向队列就能解决的问题。
具体对比差异详见:https://blog.csdn.net/SeekN/article/details/114231727
贴下代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int findBottomLeftValue(TreeNode root) {
Deque<TreeNode> deque = new ArrayDeque<TreeNode>();
deque.offer(root);
int ans = 0;
while (!deque.isEmpty()) {
TreeNode cur = deque.poll();
// 从右到左,确保左节点是最后一个
if (cur.right != null) {
deque.offer(cur.right);
}
if (cur.left != null) {
deque.offer(cur.left);
}
ans = cur.val;
}
return ans;
}
}