首页 > 代码库 > 513. Find Bottom Left Tree Value
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); } }
513. Find Bottom Left Tree Value
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。