513. 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.
现在开始考bfs 了吗, 根据size办事,分情况了
public int findBottomLeftValue(TreeNode root) { if (root == null) return -1; Queue<TreeNode> q = new LinkedList<>(); q.offer(root); int ans = 1; while (!q.isEmpty()) { int size = q.size(); for (int i = 0; i < size; i++) { TreeNode cur = q.poll(); if (cur.left != null) { q.offer(cur.left); } if (cur.right != null) { q.offer(cur.right); } if (i == 0) { ans = cur.val; } } } return ans; }
dfs: 先序遍历 + 树的深度, 跟此题类似: 199 Binary Tree Right Side View
public class Solution { int deep = 0; int ans = -1; public int findBottomLeftValue(TreeNode root) { if (root == null) return -1; //int curDeep = 0; dfs(root, 0); return ans; } private void dfs(TreeNode root, int curDeep) { if (root == null) { return; } if (root.left == null && root.right == null && deep == curDeep) { deep++; ans = root.val; return; } if (deep == curDeep) { deep++; //curDeep++; } dfs(root.left, curDeep + 1); dfs(root.right, curDeep + 1); } }